def do_321_dendro_temperatures_sharp():
    from dendrograms import dend321
    catalog, tcube = measure_dendrogram_properties(dend=dend321,
                                                   cube303=cube303,
                                                   cube321=cube321,
                                                   sncube=sncube, suffix="",
                                                   line='321',
                                                   write=False)
    catalog.write(tpath('PPV_H2CO_Temperature_321selected.ipac'), format='ascii.ipac')
    tcube.write(hpath('TemperatureCube_Dendrogram321Objects.fits'), overwrite=True)

    return catalog,tcube
def do_321_dendro_temperatures_sharp():
    from dendrograms import dend321
    catalog, tcube = measure_dendrogram_properties(dend=dend321,
                                                   cube303=cube303,
                                                   cube321=cube321,
                                                   sncube=sncube,
                                                   suffix="",
                                                   line='321',
                                                   write=False)
    catalog.write(tpath('PPV_H2CO_Temperature_321selected.ipac'),
                  format='ascii.ipac')
    tcube.write(hpath('TemperatureCube_Dendrogram321Objects.fits'),
                overwrite=True)

    return catalog, tcube
def do_321_dendro_temperatures_smooth():
    from dendrograms import dend321sm
    assert sncubesm._wcs is cube303sm._wcs
    catalog, tcube = measure_dendrogram_properties(dend=dend321sm,
                                                   cube303=cube303sm,
                                                   cube321=cube321sm,
                                                   cube13co=cube13cosm,
                                                   cube18co=cube18cosm,
                                                   noise_cube=sm_noise_cube,
                                                   sncube=sncubesm,
                                                   suffix="_smooth",
                                                   line='321',
                                                   write=False)

    catalog.write(tpath('PPV_H2CO_Temperature_321selected_smooth.ipac'), format='ascii.ipac')
    tcube.write(hpath('TemperatureCube_Dendrogram321Objects_smooth.fits'), overwrite=True)

    return catalog, tcube
def do_321_dendro_temperatures_smooth():
    from dendrograms import dend321sm
    assert sncubesm._wcs is cube303sm._wcs
    catalog, tcube = measure_dendrogram_properties(dend=dend321sm,
                                                   cube303=cube303sm,
                                                   cube321=cube321sm,
                                                   cube13co=cube13cosm,
                                                   cube18co=cube18cosm,
                                                   noise_cube=sm_noise_cube,
                                                   sncube=sncubesm,
                                                   suffix="_smooth",
                                                   line='321',
                                                   write=False)

    catalog.write(tpath('PPV_H2CO_Temperature_321selected_smooth.ipac'),
                  format='ascii.ipac')
    tcube.write(hpath('TemperatureCube_Dendrogram321Objects_smooth.fits'),
                overwrite=True)

    return catalog, tcube
示例#5
0
from astropy.table import Table
import paths

to_remove = ['v_cen', 'r303321', 'er303321', '_idx']
to_rename = {'ratio321303': 'ratio303321',
             'eratio321303': 'eratio303321',
            }


flp = Table.read(paths.tpath('fitted_line_parameters_Chi2Constraints.ipac'), format='ascii.ipac')

for col in to_remove:
    if col in flp.colnames:
        print("removing {0} from flp".format(col))
        flp.remove_column(col)
for col in to_rename:
    if col in flp.colnames:
        print("Renaming {0} to {1} in flp".format(col, to_rename[col]))
        flp.rename_column(col, to_rename[col])


p2t = Table.read(paths.tpath('PPV_H2CO_Temperature_orbit.ipac'), format='ascii.ipac')

for col in to_remove:
    if col in p2t.colnames:
        print("removing {0} from p2t".format(col))
        p2t.remove_column(col)
for col in to_rename:
    if col in p2t.colnames:
        print("Renaming {0} to {1} in p2t".format(col, to_rename[col]))
        p2t.rename_column(col, to_rename[col])
    okvelos = [
        data[name]['peak{0}velo'.format(ii)] for ii in range(4)
        if (minvelo < data[name]['peak{0}velo'.format(ii)]) and (
            data[name]['peak{0}velo'.format(ii)] < maxvelo)
    ]
    if okvelos:
        velo = np.mean(u.Quantity(okvelos))
        data[name]['mean_velo'] = velo
    else:
        data[name]['mean_velo'] = np.nan * u.km / u.s

    fig.savefig(
        paths.fpath(
            "spectral_overlays/{name}_overlaid_spectra.png".format(name=name)))

firstentry = list(data.keys())[0]
colnames = list(data[firstentry].keys())
coltypes = {k: type(data[firstentry][k]) for k in colnames}
names = Column([name for name in data], name='SourceID')
data_list = [
    Column(u.Quantity([data[name][key]
                       for name in names]), name=key) if coltypes[key]
    not in (str, ) else Column([data[name][key] for name in names], name=key)
    for key in colnames
]
data_list.insert(0, names)

tbl = Table(data_list)
tbl.sort('SourceID')
tbl.write(paths.tpath("core_velocities.ipac"), format="ascii.ipac")
示例#7
0
import numpy as np
import paths
import pyregion
from astropy import coordinates
from astropy import units as u
from astropy import table
from astropy.table import Table, Column
import latex_info
from latex_info import latexdict, exp_to_tex, format_float

tbl = Table.read(paths.tpath('fitted_line_parameters_Chi2Constraints.ipac'),
                 format='ascii.ipac')


def make_column(colname,
                errcolname,
                outcolname,
                unit,
                formatstr="${0:0.2f}\pm{1:0.2f}$"):
    data = [
        formatstr.format(d, e) for d, e in zip(tbl[colname], tbl[errcolname])
    ]
    return Column(data=data, name=outcolname, unit=unit)


def make_column_asymm(colname,
                      errlowcolname,
                      errhighcolname,
                      outcolname,
                      unit,
                      formatstr="${0:0.2f}^{{+{1:0.2f}}}_{{-{2:0.2f}}}$"):
示例#8
0
ra.set_axislabel("RA (J2000)", fontsize=pl.rcParams['axes.labelsize'])
dec.set_axislabel("Dec (J2000)", fontsize=pl.rcParams['axes.labelsize'], minpad=0)
ra.ticklabels.set_fontsize(tick_fontsize)
ra.set_ticks(exclude_overlapping=True)
dec.ticklabels.set_fontsize(tick_fontsize)
dec.set_ticks(exclude_overlapping=True)

scalebarpos = coordinates.SkyCoord("17:47:27.5", "-28:26:00.0",
                                   unit=(u.h, u.deg), frame='fk5')
make_scalebar(ax, scalebarpos,
              length=(2.0*u.pc / distance).to(u.arcsec,
                                              u.dimensionless_angles()),
              color='k',
              label='2 pc',
              text_offset=1.0*u.arcsec,
             )

fig.savefig(paths.fpath("HC3N_contours_on_SCUBA_column.pdf"), bbox_inches='tight')

core_phot_tbl = Table.read(paths.tpath("continuum_photometry.ipac"), format='ascii.ipac')
cores = coordinates.SkyCoord(core_phot_tbl['RA'], core_phot_tbl['Dec'],
                             frame='fk5')
markersize = 6
tr_fk5 = ax.get_transform("fk5")
coredots, = ax.plot(cores.ra, cores.dec, '.', color='lime', transform=tr_fk5,
                    markersize=markersize, zorder=50)
ax.axis([195,340,180,320])

fig.savefig(paths.fpath("HC3N_contours_on_SCUBA_column_withcores.pdf"),
            bbox_inches='tight')
import numpy as np
import paths
import pyregion
from astropy import coordinates
from astropy import units as u
from astropy import table
from astropy.table import Table, Column
import latex_info
from latex_info import latexdict, exp_to_tex, format_float

tbl = Table.read(paths.tpath("PPV_H2CO_Temperature.ipac"), format="ascii.ipac")


def make_column(colname, errcolname, outcolname, unit, formatstr="${0:0.2f}\pm{1:0.2f}$"):
    data = [formatstr.format(d, e) for d, e in zip(tbl[colname], tbl[errcolname])]
    return Column(data=data, name=outcolname, unit=unit)


def make_column_asymm(
    colname, errlowcolname, errhighcolname, outcolname, unit, formatstr="${0:0.2f}^{{+{1:0.2f}}}_{{-{2:0.2f}}}$"
):
    data = [
        formatstr.format(d, el, eh)
        for d, el, eh in zip(tbl[colname], tbl[colname] - tbl[errlowcolname], tbl[errhighcolname] - tbl[colname])
    ]
    return Column(data=data, name=outcolname, unit=unit)


columns = {"_idx": "Source ID", "DespoticTem": "$T_{gas, turb}$", "logh2column": "log($n(H_2)$)"}
#'spline_h2coratio321303': '$R_1$',
#'espline_h2coratio321303': '$\sigma(R_1)$',}
import numpy as np
from astropy import table
from astropy import units as u

import paths
from lte_modeling_tools import (rovib_lte_model_generator,
                                simple_lte_model_generator, kkms_of_nupper,
                                nupper_of_kkms)


tbl = table.Table.read(paths.tpath('fitted_stacked_lines.txt'), format='ascii.fixed_width')

kcl35mask = np.array([(not hasattr(row['Species'], 'mask')) and
                     ('KCl' == row['Species'][:3] or
                      '39K-35Cl' in row['Species']) for row in tbl])
kcl35tbl = tbl[kcl35mask]

v0 = np.array(['v=0' in row['Species'] for row in kcl35tbl])


# Using LTE modeling tools, what integrated intensity do we expect for each
# line for some arbitrary column density (we are ignoring optical depth) for a
# high excitation temperature?
#
# this is split out from kcl_rotational_diagrams.py
mod = simple_lte_model_generator()
mod.tem = 1000
mod.logcolumn = np.log(1e9)
fluxes = kkms_of_nupper(np.exp(mod(kcl35tbl[v0]['EU_K'])),
                        kcl35tbl[v0]['Frequency'],
                        kcl35tbl[v0]['Aij'],
import regions
import latex_info

from constants import distance

import reproject
from astropy import wcs
from astropy.io import fits
# workaround for new regions API
arbitrary_wcs = wcs.WCS(
    fits.getheader(
        paths.Fpath(
            'merge/continuum/SgrB2_selfcal_full_TCTE7m_selfcal5_ampphase_taylorterms_multiscale_deeper_mask2.5mJy.image.tt0.pbcor.fits'
        )))

core_phot_tbl = Table.read(paths.tpath("continuum_photometry_withSIMBAD.ipac"),
                           format='ascii.ipac')
core_phot_tbl.add_column(
    Column(name='radius', data=np.zeros(len(core_phot_tbl)) + np.nan))

# measured from core_flux_distributions
core_powerlaw_index = 1.94

kroupa = imf.Kroupa()

o_mmin = 8
hii_cutoff = 20

mmax = 150
over8fraction150 = (kroupa.m_integrate(o_mmin, mmax)[0] /
                    kroupa.m_integrate(kroupa.mmin, mmax)[0])
示例#12
0
        if k not in pruned_ppcat.keys():
            pruned_ppcat.add_column(Column(name=k, data=columns[k]))

    for k in pruned_ppcat.colnames:
        if "." in k:
            pruned_ppcat.rename_column(k, k.replace(".","p"))

annulus_mean = ((pruned_ppcat['cont_flux0p4arcsec']-pruned_ppcat['cont_flux0p2arcsec']) /
                (np.pi*(0.4-0.2)**2/pixel_scale_as**2) * ppbeam)
core_ish = pruned_ppcat['peak_cont_flux'] > annulus_mean
pruned_ppcat.add_column(Column(data=core_ish, name='corelike'))

pruned_ppcat.meta = {'keywords':
                     {'ppbeam': {'value': ppbeam},
                      'beam_area_sr': {'value': beam.sr.value},
                      'pixel_scale_as': {'value': pixel_scale_as},
                      'mass_conversion_factor': {'value': masscalc.mass_conversion_factor()},
                      'column_conversion_factor': {'value': masscalc.col_conversion_factor(beam.sr)},
                     }
                    }

pruned_ppcat.write(paths.tpath("dendrogram_continuum_catalog.ipac"),
                   format='ascii.ipac')

with open(paths.rpath("dendrogram_cores.reg"), 'w') as fh:
    fh.write("fk5\n")
    for row in pruned_ppcat:
        fh.write("ellipse({x_cen}, {y_cen}, {major_sigma}, "
                 "{minor_sigma}, {position_angle}) # text={{{_idx}}}\n"
                 .format(**dict(zip(row.colnames, row))))
abundance = 1e-9
# Compute brightness as a function of density for fixed abundance for two temperatures
pars = ("T_B", "tau", "Tex")
if "results" not in locals():
    results = {
        tem: {
            dens: {
                k: v
                for k, v in zip(pars, R(abundance=abundance, collider_densities={"H2": dens}, temperature=tem)[pars][2])
            }
            for dens in np.logspace(3, 8, 100)
        }
        for tem in [30, 60]
    }

emi_tbl = Table.read(paths.tpath("H2CO22_emission_spectral_fits.ecsv"), format="ascii.ecsv")
measured_brightness = emi_tbl["Amplitude"] * 32.398

tb_60 = np.array([row["T_B"] for row in results[60].values()])
bestdens_60 = [results[60].keys()[np.argmin(np.abs(tb_60 - mb))] for mb in measured_brightness] * u.cm ** -3
print("Density estimates for T=60: ", np.log10(bestdens_60.value))
tb30 = np.array([row["T_B"] for row in results[30].values()])
bestdens30 = [results[30].keys()[np.argmin(np.abs(tb30 - mb))] for mb in measured_brightness] * u.cm ** -3
print("Density estimates for T=30: ", np.log10(bestdens30.value))


distance = 5.41 * u.kpc
linewidth = 5 * u.km / u.s
sourcearea = (emi_tbl["$\Omega_{ap}$"] * distance ** 2).to(u.cm ** 2)
sourcesize = sourcearea ** 0.5
particle_mass = 2.8 * u.Da
from constants import distance

import paths

datapath = '/Users/adam/work/sgrb2/continuumdata/scuba_herschel_merge'

scubafile = fits.open(os.path.join(datapath, 'scuba_shifted_MJySr.fits'))[0]

sgrb2contfile = fits.open(
    paths.Fpath(
        'merge/continuum/SgrB2_selfcal_full_TCTE7m_selfcal5_ampphase_taylorterms_multiscale_deeper_mask2.5mJy.image.tt0.pbcor.fits'
    ))

tbl = table.Table.read(
    paths.tpath("continuum_photometry.ipac"),
    format='ascii.ipac',
)
coords = coordinates.SkyCoord(tbl['RA'],
                              tbl['Dec'],
                              frame='fk5',
                              unit=(u.deg, u.deg))
mywcs = wcs.WCS(scubafile.header)
xpix, ypix = mywcs.wcs_world2pix(np.transpose([coords.ra.deg, coords.dec.deg]),
                                 0).T
xpix = np.round(xpix).astype('int')
ypix = np.round(ypix).astype('int')

observed_region, _ = reproject.reproject_interp(sgrb2contfile,
                                                scubafile.header)
示例#15
0
               bbox_inches='tight')
    L.set_visible(False)

    if smooth:
        ax3.set_xlim(-0.1,4.6)
    else:
        ax3.set_xlim(-0.0,4.6)
    ax3.text(bricktime+3.58, ytext*135./140., "20 km s$^{-1}$", verticalalignment='center',
             horizontalalignment='center', rotation='vertical', color='k', weight='bold')
    ax3.text(bricktime+3.66, ytext*135./140., "50 km s$^{-1}$", verticalalignment='center',
             horizontalalignment='center', rotation='vertical', color='k', weight='bold')
    ax3.text(bricktime+3.28, ytext, "Sgr C", verticalalignment='center',
             horizontalalignment='center', rotation='vertical', color='k', weight='bold')

    pl.savefig(fpath("orbits/dendro{0}_temperature_vs_time.pdf".format(smooth)),
               bbox_inches='tight')

    L.set_visible(True)
    pl.savefig(fpath("orbits/dendro{0}_temperature_vs_time_trendline.pdf".format(smooth)),
               bbox_inches='tight')

    fig4 = pl.figure(4, figsize=(14,8))
    fig4.clf()
    ax4 = fig4.gca()
    if np.any(selection&is_leaf):
        ax4.hist(cat['temperature_chi2'][selection&is_leaf], histtype='stepfilled', edgecolor='none', alpha=0.5)
    if np.any((~selection)&is_leaf):
        ax4.hist(cat['temperature_chi2'][(~selection)&is_leaf], histtype='stepfilled', edgecolor='none', alpha=0.5)

catalog.write(paths.tpath('PPV_H2CO_Temperature_orbit.ipac'), format='ascii.ipac')
threshold_density_40 = (masscalc.mass_conversion_factor(TK=40) * (threshold*u.beam).to(u.mJy).value /
                        (4/3.*np.pi) /
                        (beam.sr.value*masscalc.distance**2)**(1.5) /
                        (2.8*constants.m_p)).to(1/u.cm**3)
print("Threshold density (40K): {0:e}".format(threshold_density_40))
flux_of_filament = 132*u.Jy/u.beam/ppbeam
print("Total *filament* mass(40K): {0}".format(flux_of_filament * masscalc.mass_conversion_factor(TK=40)*u.M_sun/u.Jy))
print("Total *filament* mass(100K): {0}".format(flux_of_filament * masscalc.mass_conversion_factor(TK=100)*u.M_sun/u.Jy))
print("Filament line mass: {0}".format(flux_of_filament *
                                       masscalc.mass_conversion_factor() *
                                       u.M_sun/u.Jy /
                                       (0.0027*u.deg*masscalc.distance).to(u.pc, u.dimensionless_angles())
                                      )
     )

dendro_merge = Table.read(paths.tpath('dendro_merge_continuum_and_line.ipac'), format='ascii.ipac')
corelike = dendro_merge['corelike'] == 'True'
dendro_protostars_pt2 = dendro_merge['cont_flux0p2arcsec'].sum()*u.Jy
print("Total protostar flux (0.2): {0}".format(dendro_protostars_pt2))
print("Total protostar flux (peak): {0}".format(dendro_merge['peak_cont_flux'].sum()*u.Jy))
total_minus_protostars = total_signal - dendro_protostars_pt2
print("Total recovered flux minus protostars: {0}".format(total_minus_protostars))
print("Total mass minus protostars (20K): {0}".format(total_minus_protostars * masscalc.mass_conversion_factor()*u.M_sun/u.Jy))

# determine BGPS total mass
regions = pyregion.open(paths.rpath("12m_pointings.reg"))
bgps_fh = fits.open("/Users/adam/work/w51/v2.0_ds2_l050_13pca_map20.fits")
mask = regions.get_mask(bgps_fh[0])
bgps_sum = bgps_fh[0].data[mask].sum() * u.Jy
bgps_ppbeam = bgps_fh[0].header['PPBEAM']
bgps_totalflux = bgps_sum/bgps_ppbeam
        F.scalebar.set_color('w')
        #F.set_tick_xspacing(0.0005)
        F.add_label(0.05, 0.95, rlabel, relative=True, color='r', horizontalalignment='left')
        F.add_label(0.05, 0.91, glabel, relative=True, color='g', horizontalalignment='left')
        F.add_label(0.05, 0.87, blabel, relative=True, color='b', horizontalalignment='left')
        F.save(paths.fpath("W51e2_{0}_aplpy.png".format(name)))
        F.save(paths.fpath("W51e2_{0}_aplpy.pdf".format(name)))

        cmcontsrc = Table.read(paths.vpath('tables/EVLA_VLA_PointSourcePhotometry.ipac'),
                               format='ascii.ipac')
        cmok = (cmcontsrc['Frequency']==5.9) & (cmcontsrc['Epoch']=='3')
        cmcoords = coordinates.SkyCoord(cmcontsrc['gracen'][cmok],
                                        cmcontsrc['gdeccen'][cmok], frame='fk5')


        core_phot_tbl = Table.read(paths.tpath("continuum_photometry.ipac"), format='ascii.ipac')
        cores = coordinates.SkyCoord(core_phot_tbl['RA'], core_phot_tbl['Dec'],
                                     frame='fk5')

        F.show_markers(cmcoords.ra, cmcoords.dec, edgecolor=star_color, marker='*', alpha=0.75,
                       zorder=1, facecolor=star_color, layer='hiiregions')
        #F.hide_layer('hiiregions_text')
        F.save(paths.fpath("W51e2_{0}_aplpy_hiiregions.png".format(name)))
        F.save(paths.fpath("W51e2_{0}_aplpy_hiiregions.pdf".format(name)))

        F.show_markers(cores.ra, cores.dec, edgecolor=core_color, marker='.', alpha=0.9,
                       zorder=1, facecolor=core_color, layer='cores')
        F.save(paths.fpath("W51e2_{0}_aplpy_hiiregions_cores.png".format(name)))
        F.save(paths.fpath("W51e2_{0}_aplpy_hiiregions_cores.pdf".format(name)))

        F.hide_layer('hiiregions')
from __future__ import print_function
import numpy as np
from astropy import units as u
from astropy import table
import paths
from astropy import time
from rounded import rounded
from latex_info import latexdict, format_float
from astropy.table import Table
import copy

latexdict = copy.copy(latexdict)
tbl = Table.read(paths.tpath('EVLA_VLA_PointSourcePhotometry.ipac'), format='ascii.ipac')

## Create latex table

tbl.add_column(table.Column(data=tbl['peak_flux']-tbl['cutout_min_flux'],
                            name='peak_m_background',
                            unit=tbl['peak_flux'].unit))
nondetections = tbl['peak_m_background'] < tbl['local_rms_noise']*3

cols_order = ['SourceName', 'Epoch', 'ObservationDate', 'peak_flux', 'peak_m_background', 'local_rms_noise', 'Frequency']
cols = {'SourceName': 'Object',
        #'FrequencyName': 'Band',
        'ObservationDate': 'Obs. Date',
        'peak_flux': 'Peak $S_{\\nu}$',
        'peak_m_background': 'Peak - Background',
        'local_rms_noise': 'RMS',
       }

textbl = tbl.copy()[cols_order]
import numpy as np
from astropy.table import Table
import paths
from latex_info import latexdict, exp_to_tex, format_float
import natsort

tbl = Table.read("../tables/obs_meta.tbl", format="ascii", delimiter="|")

tbl = tbl[natsort.index_natsorted(tbl["Date"])]

latexdict["header_start"] = "\label{tab:obs_meta}"
latexdict["caption"] = "Observation Metadata"
latexdict["tablefoot"] = ""
latexdict["col_align"] = "l" * 8
# latexdict['tabletype'] = 'longtable'
# latexdict['tabulartype'] = 'longtable'
tbl.write(paths.tpath("obs_meta.tex"), format="ascii.latex", latexdict=latexdict, formats={}, overwrite=True)
示例#20
0
# Workaround / bugfix for https://github.com/astropy/astropy/issues/2974
def fix_logical(t):
    newcols = []
    for col in t.columns.values():
        if col.dtype.str.endswith('S5'):
            falses = col == 'False'
            trues = col == 'True'
            if np.all(falses | trues):
                col = t.ColumnClass(trues, name=col.name)
        newcols.append(col)
    return Table(newcols)

dend_sm = dendsm

try:
    catalog = fix_logical(Table.read(tpath('PPV_H2CO_Temperature.ipac'),
                                     format='ascii.ipac', guess=False))
    catalog_sm = fix_logical(Table.read(tpath('PPV_H2CO_Temperature_smooth.ipac'),
                             format='ascii.ipac', guess=False))
    catalogsm = catalog_sm

except IOError:
    warnings.warn("Need to run dendro_temperature:do_dendro_temperatures_both"
                  " to get the PPV H2CO catalogs first")


#try:
#    catalog321 = Table.read(hpath('PPV_H2CO_Temperature_321selected.ipac'),
#                            format='ascii.ipac', guess=False)
#    catalog321_sm = Table.read(hpath('PPV_H2CO_Temperature_321selected_smooth.ipac'),
#                               format='ascii.ipac', guess=False)
        if k not in pruned_ppcat.keys():
            pruned_ppcat.add_column(Column(name=k, data=columns[k]))

    for k in pruned_ppcat.colnames:
        if "." in k:
            pruned_ppcat.rename_column(k, k.replace(".","p"))

annulus_mean = ((pruned_ppcat['cont_flux0p4arcsec']-pruned_ppcat['cont_flux0p2arcsec']) /
                (np.pi*(0.4-0.2)**2/pixel_scale_as**2) * ppbeam)
core_ish = pruned_ppcat['peak_cont_flux'] > annulus_mean
pruned_ppcat.add_column(Column(data=core_ish, name='corelike'))

pruned_ppcat.meta = {'keywords':
                     {'ppbeam': {'value': ppbeam},
                      'beam_area_sr': {'value': beam.sr.value},
                      'pixel_scale_as': {'value': pixel_scale_as},
                      'mass_conversion_factor': {'value': masscalc.mass_conversion_factor()},
                      'column_conversion_factor': {'value': masscalc.col_conversion_factor(beam.sr)},
                     }
                    }

pruned_ppcat.write(paths.tpath("dendrogram_continuum_catalog.ipac"),
                   format='ascii.ipac')

with open(paths.rpath("dendrogram_cores.reg"), 'w') as fh:
    fh.write("fk5\n")
    for row in pruned_ppcat:
        fh.write("ellipse({x_cen}, {y_cen}, {major_sigma}, "
                 "{minor_sigma}, {position_angle}) # text={{{_idx}}}\n"
                 .format(**dict(zip(row.colnames, row))))
示例#22
0
#salt_tables = [KCl, K37Cl, K41Cl, NaCl, Na37Cl, K41Cl37]
salt_colors = ['b', 'm', 'darkgreen', 'orange', 'c', 'y']
tables = []

def linename(row):
    return "{0} {1}".format(row['Species'], row['QNs'])
def freq(row):
    return u.Quantity(row['Freq'], u.GHz)

linenames = [linename(row) for tbl in tables for row in tbl]
linetexnames = [linename(row) for tbl in tables for row in tbl] + ided_linetexnames
linefreqs = np.hstack([u.Quantity([freq(row) for tbl in tables for row in tbl], u.GHz).value,
                       ided_linefreqs.value])
linefreqs = u.Quantity(linefreqs, u.GHz)

detection_table = table.Table.read(paths.tpath('salts_in_band.ipac'), format='ascii.ipac')
nondetections = (detection_table['Flag'] == '-n') | (detection_table['Flag'] == 'cn')
detection_table = detection_table[~nondetections]



flist = [fn] if 'fn' in locals() else glob.glob(paths.dpath('stacked_spectra/OrionSourceI_*robust0.5.fits'))
for fn in flist:
    print(fn)

    sp_st = pyspeckit.Spectrum(fn)

    pl.figure(0, figsize=(16,6)).clf()
    sp_st.plotter(figure=pl.figure(0, figsize=(16,6)), clear=True)

    basefn = os.path.split(fn)[-1]
                 list((rounded(thisspec.specfit.parinfo.AMPLITUDE0.value, thisspec.specfit.parinfo.AMPLITUDE0.error)*u.Jy).to(u.mJy))+
                 list(rounded(thisspec.specfit.parinfo.SHIFT0.value, thisspec.specfit.parinfo.SHIFT0.error)*u.km/u.s)+
                 list(rounded(thisspec.specfit.parinfo.WIDTH0.value, thisspec.specfit.parinfo.WIDTH0.error)*u.km/u.s)+
                 [np.round(thisspec.header['APAREA']*(np.pi/180.)**2, int(np.ceil(-np.log10(thisspec.header['APAREA']*(np.pi/180.)**2)))+1)*u.sr])

 
# sort such that e10 comes after e9
import natsort
tbl = tbl[natsort.index_natsorted(tbl['Object Name'])]

detection_note = ['-' if name in detections else
                  'ambig' if name in ambiguousdetections else
                  'none'
                  for name in tbl['Object Name']]
tbl.add_column(table.Column(data=detection_note, name='Detection Status'))

ok = np.array([row['Object Name'] in detections+ambiguousdetections
               for row in tbl])

tbl[ok].write(paths.tpath('H2CO22_hiiregion_spectral_fits.ecsv'), format='ascii.ecsv')

for row in tbl:
    if "_" in row['Object Name']:
        row['Object Name'] = row['Object Name'].replace("_","\_")

latexdict['header_start'] = '\label{tab:absorption22}'
latexdict['caption'] = '\\formaldehyde \\twotwo absorption line parameters'
tbl[ok].write(paths.tpath('H2CO22_hiiregion_spectral_fits.tex'), format='ascii.latex', latexdict=latexdict,
              formats={'$\Omega_{ap}$': format_float}
             )
Determine velocities *and* peak_TB's
"""
import numpy as np
import paths
import pyspeckit
import pylab as pl
from astropy import constants
from astropy.io import fits
from astropy.table import Table,Column
from astropy import units as u
from astropy import log
import spectral_overlays

from line_parameters import frequencies, freq_name_mapping, yoffset

pruned_ppcat = Table.read(paths.tpath("dendrogram_continuum_catalog.ipac"),
                          format='ascii.ipac')
dendromask = fits.getdata(paths.apath('dendrograms_min1mJy_diff1mJy_mask_pruned.fits'))

minvelo = 45*u.km/u.s
maxvelo = 90*u.km/u.s

# array merged
data = {}

for row in pruned_ppcat:
    name = row['_idx']
    data[name] = {}

    fn = paths.merge_spath("dendro{name:03d}_spw{ii}_mean_7m12m.fits")
    bgfn = paths.merge_spath("dendro{name:03d}_spw{ii}_background_mean_7m12m.fits")
                               reg in points+diffuse])
radii = ([(reg.coord_list[2]) if len(reg.coord_list) > 2 else np.nan
          for reg in points+diffuse]*u.deg).to(u.arcsec)
names = [reg.attr[1]['text'] for reg in points+diffuse]
                              
postbl = Table([Column(data=names, name='Source Name'),
                Column(data=coords.ra.to_string(unit=u.hour, sep=':'), name='RA'),
                Column(data=coords.dec.to_string(unit=u.deg, sep=':'), name='Dec'),
                Column(data=radii, name='Radius'),
                Column(data=(radii*5.1*u.kpc).to(u.pc, u.dimensionless_angles()), name='Phys. Radius'),
               ])
postbl.sort('Source Name')

latexdict['header_start'] = '\label{tab:positions}'
latexdict['caption'] = 'Source Positions'
latexdict['tablefoot'] = ('\par\nObjects with name e\#d are the diffuse '
                          'counterparts to point sources.  Those with a '
                          'trailing ? are candidate sources that are only weakly '
                          'detected.   Sources with no radius are unresolved, '
                          'with '
                          'upper limits of 0.3\\arcsec (0.007 pc).')
latexdict['col_align'] = 'lllrr'
#latexdict['tabletype'] = 'longtable'
#latexdict['tabulartype'] = 'longtable'
postbl.write(paths.tpath('source_positions.tex'), format='ascii.latex',
             latexdict=latexdict,
             formats={'Radius': lambda x: '-' if np.isnan(x) else '{0:0.2f}'.format(x),
                      'Phys. Radius': lambda x: '-' if np.isnan(x) else '{0:0.2f}'.format(x),
                     },
            )
示例#26
0
import numpy as np
import paths
from astropy.table import Table, Column
from astropy import table
from astropy import units as u
from astropy import coordinates
import masscalc

dendro_velo_tbl = Table.read(paths.tpath("dendro_core_velocities.ipac"), format="ascii.ipac")
dendro_phot_tbl = Table.read(paths.tpath("dendrogram_continuum_catalog.ipac"), format='ascii.ipac')

dendro_phot_tbl.rename_column('_idx','SourceID')
dendro_merge = table.join(dendro_velo_tbl, dendro_phot_tbl,)

brightest_line_flux = np.array([dendro_merge[y].data for y in
                                ('peak0','peak1','peak2','peak3')])
peak_line_flux = np.nanmax(brightest_line_flux, axis=0)
peak_line_id = np.nanargmax(np.nan_to_num(brightest_line_flux), axis=0)
peak_line_id[np.isnan(peak_line_flux)] = -999
brightest_line_name = np.array([dendro_merge[('peak0species', 'peak1species',
                                              'peak2species',
                                              'peak3species')[y]][ii]
                                if y >= 0 else 'NONE'
                                for ii,y in enumerate(peak_line_id)])
dendro_merge.add_column(Column(peak_line_flux, name='PeakLineFlux',
                               unit=dendro_merge['peak0'].unit))
dendro_merge.add_column(Column(brightest_line_name, name='PeakLineSpecies'))

peak_line_beam_area = u.Quantity([dendro_merge['beam{0}area'.format(pid)][ii]
                                  if pid >= 0 else 1.0
                                  for ii,pid in enumerate(peak_line_id)],
示例#27
0
                                          ).value
                               for bm,freq in zip(beams.values(),
                                                  obstbl['Frequency'])
                              ],
                         name='Jy-Kelvin'
                        )
                 )

obstbl.sort(['Frequency', 'Epoch'])
latexdict['header_start'] = '\label{tab:observations}'
latexdict['caption'] = 'Observations'
latexdict['tablefoot'] = ('\par\nJy-Kelvin gives the conversion factor from Jy '
                          'to Kelvin given the synthesized beam size and '
                          'observation frequency.')
#latexdict['col_align'] = 'lllrr'
#latexdict['tabletype'] = 'longtable'
#latexdict['tabulartype'] = 'longtable'
def round_to_n(x, n):
    return round(x, -int(np.floor(np.log10(x))) + (n - 1))
obstbl.write(paths.tpath('observations.tex'), format='ascii.latex',
             latexdict=latexdict,
             formats={'BMAJ': lambda x: '{0:0.2f}'.format(x),
                      'BMIN': lambda x: '{0:0.2f}'.format(x),
                      'BPA':  lambda x: '{0:0}'.format(int(x)),
                      'Noise Estimate': lambda x: '{0:0.2f}'.format(x),
                      'Dynamic Range': lambda x: '{0:d}'.format(int(round_to_n(x, 2))),
                      'Jy-Kelvin':  format_float,
                     },
            )
 
import numpy as np
import paths
from astropy.table import Table, Column
from astropy import table
from astropy import units as u
import masscalc

outflow_tbl = Table.read(paths.tpath("outflow_co_photometry.ipac"), format='ascii.ipac')
core_velo_tbl = Table.read(paths.tpath("core_velocities.ipac"), format="ascii.ipac")
core_phot_tbl = Table.read(paths.tpath("continuum_photometry.ipac"), format='ascii.ipac')
outflow_tbl.meta.update(core_phot_tbl.meta)
ppbeam = core_phot_tbl.meta['keywords']['ppbeam_mm']['value']


core_phot_tbl.rename_column('name','SourceID')
cores_merge = table.join(core_velo_tbl, core_phot_tbl,)

brightest_line_flux = np.array([cores_merge[y].data for y in ('peak0','peak1','peak2','peak3')])
peak_line_flux = np.nanmax(brightest_line_flux, axis=0)
peak_line_id = np.nanargmax(brightest_line_flux, axis=0)
brightest_line_name = np.array([cores_merge[('peak0species','peak1species','peak2species','peak3species')[y]][ii] for ii,y in enumerate(peak_line_id)])
cores_merge.add_column(Column(peak_line_flux, name='PeakLineFlux', unit=cores_merge['peak0'].unit))
cores_merge.add_column(Column(brightest_line_name, name='PeakLineSpecies'))

peak_line_brightness = (peak_line_flux*u.Jy).to(u.K, u.brightness_temperature(cores_merge['beam_area'], 220*u.GHz))
cores_merge.add_column(Column(peak_line_brightness, name='PeakLineBrightness'))

jtok_eq = u.brightness_temperature(cores_merge['beam_area'], 225*u.GHz)
cont_brightness = Column((u.beam * cores_merge['sum']/cores_merge['npix']).to(u.K, jtok_eq),
                         name='MeanContinuumBrightness')
cores_merge.add_column(cont_brightness)
        ax.yaxis.set_ticklabels([])
        ax.yaxis.set_label("")
        if ii < plotnum-7:
            ax.xaxis.set_ticklabels([])
            ax.xaxis.set_label("")

    pl.savefig(paths.fpath('spectral_fits/{0}_linefits.png'.format(name)),
               bbox_inches='tight', bbox_extra_artists=[])

    pl.figure(2).clf()
    widths = line_table['{0}FittedWidth'.format(name)]
    ewidths = line_table['{0}FittedWidthError'.format(name)]
    labels = line_table['Species']
    inds = np.argsort(widths)
    mask = (widths[inds]>0) & (widths[inds]<5) & (ewidths[inds] < widths[inds]) & (ewidths[inds] < 5)
    pl.errorbar(x=np.arange(mask.sum()),
                y=widths[inds][mask],
                yerr=ewidths[inds][mask],
                linestyle='none',
                color='k')
    ax = pl.gca()
    ax.set_xticks(np.arange(mask.sum()))
    ax.set_xticklabels(labels[inds][mask], rotation='vertical')
    ax.set_xlim(-1, mask.sum()+1)
    pl.savefig(paths.fpath('spectral_fits/{0}_linewidths.png'.format(name)),
               bbox_inches='tight', bbox_extra_artists=[])


    line_table.write(paths.tpath('spectral_lines_and_fits.csv'),
                     overwrite=True)
示例#30
0
"""
Generally meant to be run from merge_outflow_core_tables.py
"""
import numpy as np
import paths
from astropy.table import Table, Column
from astropy import table
from astropy import units as u
import masscalc

spectral_line_fit_tbl = Table.read(paths.tpath('spectral_lines_and_fits.csv'))

cores_merge = Table.read(paths.tpath('core_continuum_and_line.ipac'),
                         format='ascii.ipac')

molcld_exclude_names = ['13COv=0', 'C18O', 'H2CO', 'COv=0']
molcld_exclude = np.array([
    any(nm in row['Species'] for nm in molcld_exclude_names)
    for row in spectral_line_fit_tbl
])

brightest_noncld_lines = []
brightest_noncld_qns = []
brightest_noncld_fluxes = []
brightest_fitted_brightness = []

for row in cores_merge:
    src = row['SourceID']

    amplitudes = spectral_line_fit_tbl['{0}FittedAmplitude'.format(src)]
    noncld_amplitudes = amplitudes * ~molcld_exclude
from astropy.io import fits
from astropy import wcs
from astropy import units as u
from astropy import coordinates
import powerlaw
import pylab as pl
import scipy
from matplotlib.patches import Circle

# can take time:
from volume_integrals import mass_scalings

pl.matplotlib.rc_file('pubfiguresrc')

#pruned_ppcat = Table.read(paths.tpath("dendrogram_continuum_catalog.ipac"), format='ascii.ipac')
dendro_merge = Table.read(paths.tpath('dendro_merge_continuum_and_line.ipac'), format='ascii.ipac')
corelike = dendro_merge['corelike'] == 'True'

fig1 = pl.figure(1)
fig1.clf()
ax1 = fig1.gca()

ax1.hist(dendro_merge['peak_cont_flux'], log=True, bins=np.logspace(-3,-0.5,15))
ax1.set_xscale('log')
ax1.set_ylim(0.3, 51)


fig2 = pl.figure(2)
fig2.clf()
ax2 = fig2.add_subplot(211)
示例#32
0
import numpy as np
import paths
from astropy import coordinates
from astropy import units as u
from astropy.table import Table,Column
from latex_info import latexdict, exp_to_tex, format_float

with open(paths.tpath("associations.tbl")) as f:
    lines = f.readlines()
    split1 = lines[0].find('Xray_Association')
    split2 = lines[0].find('NIR_Association')
    split3 = lines[0].find('Goldader1994')
    xrayassociations = {x[:split1].strip():x[split1:split2].strip() for x in lines[1:]}
    nirassociations = {x[:split1].strip():x[split2:split3].strip() for x in lines[1:]}
    goldaderassociations = {x[:split1].strip():x[split3:].strip() for x in lines[1:]}
    names = sorted(xrayassociations.keys())
    keep = [name for name in names if not (xrayassociations[name]=='-' and nirassociations=='-')]
    xrayassociations_column = Column(data=[xrayassociations[x] for x in keep],
                                     name="X-ray")
    nirassociations_column = Column(data=[nirassociations[x] for x in keep],
                                    name="NIR")
    goldaderassociations_column = Column(data=[goldaderassociations[x] for x in keep],
                                    name="Goldader 1994")
    names_column = Column(data=keep, name='Source Name')

tbl = Table([names_column, xrayassociations_column, nirassociations_column,
             goldaderassociations_column])

OK = (tbl['X-ray'] != '-') | (tbl['NIR'] != '-') | (tbl['Goldader 1994'] != '-')
tbl=tbl[OK]
                               texgrid322, taugrid322, hdr)

# use the local constrain_parameters; h2co_modeling's version is... not exactly up to date.
from constrain_parameters import paraH2COmodel
from h2co_modeling import grid_fitter
from astropy import table
import despotic_heating as heating


pl.rcParams['font.size'] = 16.0
pl.close(4)

# mf means modelfitter
mf = paraH2COmodel()

fittable = table.Table.read(tpath("fitted_line_parameters.ipac"),
                            format='ascii.ipac')
fittable.add_columns([table.Column(name=name, dtype='float', length=len(fittable))
                      for name in ['temperature_chi2','tmin1sig_chi2','tmax1sig_chi2',
                                   'expected_temperature',
                                   'column_chi2','cmin1sig_chi2','cmax1sig_chi2',
                                   'expected_column',
                                   'density_chi2','dmin1sig_chi2','dmax1sig_chi2',
                                   'expected_density',
                                   'logh2column','elogh2column',
                                   'logabundance','elogabundance',
                                   'tkin_turb', 'reff_pc',
                                  ]])

if not os.path.exists(paths.fpath('param_fits')):
    os.makedirs(paths.fpath('param_fits'))
import numpy as np
import pylab as pl
from astropy.io import ascii
from astropy import table
from astropy.table import Table
import paths
from common_constants import distance
from astropy import units as u


tbl = Table.read(paths.tpath('EVLA_VLA_PointSourcePhotometry.ipac'), format='ascii.ipac')
lrad = (4*np.pi*distance**2 * tbl['peak_flux'] * u.beam * tbl['Frequency']).to(u.erg/u.s)

bieging = ascii.read(paths.tpath('bieging1989.tbl'))
beck = Table.read(paths.tpath('debecker2013.tbl'), format='ascii.commented_header')
lrad_bieging = (bieging['f6cm_hi']*u.mJy * (4*np.pi*(bieging['distance']*u.kpc)**2) * 5*u.GHz).to(u.erg/u.s)


pl.figure(1).clf()
pl.plot(bieging['mass'], np.transpose([bieging['f6cm_lo']*bieging['distance']**2,
                                       bieging['f6cm_hi']*bieging['distance']**2]),
        marker='o', linestyle='none')
pl.ylabel("$S_\\nu D^2$")
pl.xlabel("$M_\odot$")

pl.figure(2).clf()
pl.semilogx(10**bieging['luminosity'],
            np.transpose([bieging['f6cm_lo']*bieging['distance']**2,
                          bieging['f6cm_hi']*bieging['distance']**2]),
            marker='o', linestyle='none')
pl.ylabel("$S_\\nu D^2$")
    'npix': u.dimensionless_unscaled,
    'peak_mass': u.M_sun,
    'peak_col': u.cm**-2,
    'mean_col': u.cm**-2,
    'total_mass': u.M_sun,
    'pixsize': u.deg,
    'pixsize_phys': u.pc,
    'v1': u.km / u.s,
    'v2': u.km / u.s,
    'momentum': u.M_sun * u.km / u.s,
    'mean_velo': u.km / u.s,
}

suffixes = string.ascii_letters

centralv_table = Table.read(paths.tpath('core_velocities.ipac'),
                            format='ascii.ipac')

for reg in regions:
    if 'text' not in reg.attr[1]:
        continue

    shreg = pyregion.ShapeList([reg])
    name_, v1, v2 = reg.attr[1]['text'].split()
    v1 = float(v1) * u.km / u.s
    v2 = float(v2) * u.km / u.s

    # get the name before a suffix is appended
    if name_ in centralv_table['SourceID']:
        central_velo = centralv_table['mean_velo'][centralv_table['SourceID']
                                                   == name_][0] * u.km / u.s
def measure_dendrogram_properties(dend=None, cube303=cube303,
                                  cube321=cube321, cube13co=cube13co,
                                  cube18co=cube18co, noise_cube=noise_cube,
                                  sncube=sncube,
                                  suffix="",
                                  last_index=None,
                                  plot_some=True,
                                  line='303',
                                  write=True):

    assert (cube321.shape == cube303.shape == noise_cube.shape ==
            cube13co.shape == cube18co.shape == sncube.shape)
    assert sncube.wcs is cube303.wcs is sncube.mask._wcs

    metadata = {}
    metadata['data_unit'] = u.K
    metadata['spatial_scale'] =  7.2 * u.arcsec
    metadata['beam_major'] =  30 * u.arcsec
    metadata['beam_minor'] =  30 * u.arcsec
    metadata['wavelength'] =  218.22219*u.GHz
    metadata['velocity_scale'] = u.km/u.s
    metadata['wcs'] = cube303.wcs

    keys = [
            'density_chi2',
            'expected_density',
            'dmin1sig_chi2',
            'dmax1sig_chi2',
            'column_chi2',
            'expected_column',
            'cmin1sig_chi2',
            'cmax1sig_chi2',
            'temperature_chi2',
            'expected_temperature',
            'tmin1sig_chi2',
            'tmax1sig_chi2',
            'eratio321303',
            'ratio321303',
            'logh2column',
            'elogh2column',
            'logabundance',
            'elogabundance',
           ]
    obs_keys = [
            'Stot303',
            'Smin303',
            'Smax303',
            'Stot321',
            'Smean303',
            'Smean321',
            'npix',
            'e303',
            'e321',
            'r321303',
            'er321303',
            '13cosum',
            'c18osum',
            '13comean',
            'c18omean',
            's_ntotal',
            'index',
            'is_leaf',
            'parent',
            'root',
            'lon',
            'lat',
            'vcen',
            'higaldusttem',
            'reff',
            'dustmass',
            'dustmindens',
            'bad',
            #'tkin_turb',
    ]
    columns = {k:[] for k in (keys+obs_keys)}

    log.debug("Initializing dendrogram temperature fitting loop")

    # FORCE wcs to match
    # (technically should reproject here)
    cube13co._wcs = cube18co._wcs = cube303.wcs
    cube13co.mask._wcs = cube18co.mask._wcs = cube303.wcs

    if line == '303':
        maincube = cube303
    elif line == '321':
        maincube = cube321
    else:
        raise ValueError("Unrecognized line: {0}".format(line))

    # Prepare an array to hold the fitted temperatures
    tcubedata = np.empty(maincube.shape, dtype='float32')
    tcubedata[:] = np.nan
    tcubeleafdata = np.empty(maincube.shape, dtype='float32')
    tcubeleafdata[:] = np.nan


    nbad = 0

    catalog = ppv_catalog(dend, metadata)
    pb = ProgressBar(len(catalog))
    for ii,row in enumerate(catalog):
        structure = dend[row['_idx']]
        assert structure.idx == row['_idx'] == ii
        dend_obj_mask = BooleanArrayMask(structure.get_mask(), wcs=cube303.wcs)
        dend_inds = structure.indices()

        view = (slice(dend_inds[0].min(), dend_inds[0].max()+1),
                slice(dend_inds[1].min(), dend_inds[1].max()+1),
                slice(dend_inds[2].min(), dend_inds[2].max()+1),)
        #view2 = cube303.subcube_slices_from_mask(dend_obj_mask)
        submask = dend_obj_mask[view]
        #assert np.count_nonzero(submask.include()) == np.count_nonzero(dend_obj_mask.include())

        sn = sncube[view].with_mask(submask)
        sntot = sn.sum().value
        #np.testing.assert_almost_equal(sntot, structure.values().sum(), decimal=0)

        c303 = cube303[view].with_mask(submask)
        c321 = cube321[view].with_mask(submask)
        co13sum = cube13co[view].with_mask(submask).sum().value
        co18sum = cube18co[view].with_mask(submask).sum().value
        if hasattr(co13sum,'__len__'):
            raise TypeError(".sum() applied to an array has yielded a non scalar.")

        npix = submask.include().sum()
        assert npix == structure.get_npix()
        Stot303 = c303.sum().value
        if np.isnan(Stot303):
            raise ValueError("NaN in cube.  This can't happen: the data from "
                             "which the dendrogram was derived can't have "
                             "NaN pixels.")
        Smax303 = c303.max().value
        Smin303 = c303.min().value

        Stot321 = c321.sum().value
        if npix == 0:
            raise ValueError("npix=0. This is impossible.")
        Smean303 = Stot303/npix
        if Stot303 <= 0 and line=='303':
            raise ValueError("The 303 flux is <=0.  This isn't possible because "
                             "the dendrogram was derived from the 303 data with a "
                             "non-zero threshold.")
        elif Stot303 <= 0 and line=='321':
            Stot303 = 0
            Smean303 = 0
        elif Stot321 <= 0 and line=='321':
            raise ValueError("The 321 flux is <=0.  This isn't possible because "
                             "the dendrogram was derived from the 321 data with a "
                             "non-zero threshold.")
        if np.isnan(Stot321):
            raise ValueError("NaN in 321 line")
        Smean321 = Stot321/npix

        #error = (noise_cube[view][submask.include()]).sum() / submask.include().sum()**0.5
        var = ((noise_cube[dend_obj_mask.include()]**2).sum() / npix**2)
        error = var**0.5
        if np.isnan(error):
            raise ValueError("error is nan: this is impossible by definition.")

        if line == '321' and Stot303 == 0:
            r321303 = np.nan
            er321303 = np.nan
        elif Stot321 < 0:
            r321303 = error / Smean303
            er321303 = (r321303**2 * (var/Smean303**2 + 1))**0.5
        else:
            r321303 = Stot321 / Stot303
            er321303 = (r321303**2 * (var/Smean303**2 + var/Smean321**2))**0.5

        for c in columns:
            assert len(columns[c]) == ii

        columns['index'].append(row['_idx'])
        columns['s_ntotal'].append(sntot)
        columns['Stot303'].append(Stot303)
        columns['Smax303'].append(Smax303)
        columns['Smin303'].append(Smin303)
        columns['Stot321'].append(Stot321)
        columns['Smean303'].append(Smean303)
        columns['Smean321'].append(Smean321)
        columns['npix'].append(npix)
        columns['e303'].append(error)
        columns['e321'].append(error)
        columns['r321303'].append(r321303)
        columns['er321303'].append(er321303)
        columns['13cosum'].append(co13sum)
        columns['c18osum'].append(co18sum)
        columns['13comean'].append(co13sum/npix)
        columns['c18omean'].append(co18sum/npix)
        columns['is_leaf'].append(structure.is_leaf)
        columns['parent'].append(structure.parent.idx if structure.parent else -1)
        columns['root'].append(get_root(structure).idx)
        s_main = maincube._data[dend_inds]
        x,y,z = maincube.world[dend_inds]
        lon = ((z.value-(360*(z.value>180)))*s_main).sum()/s_main.sum()
        lat = (y*s_main).sum()/s_main.sum()
        vel = (x*s_main).sum()/s_main.sum()
        columns['lon'].append(lon)
        columns['lat'].append(lat.value)
        columns['vcen'].append(vel.value)

        mask2d = dend_obj_mask.include().max(axis=0)[view[1:]]
        logh2column = np.log10(np.nanmean(column_regridded.data[view[1:]][mask2d]) * 1e22)
        if np.isnan(logh2column):
            log.info("Source #{0} has NaNs".format(ii))
            logh2column = 24
        elogh2column = elogabundance
        columns['higaldusttem'].append(np.nanmean(dusttem_regridded.data[view[1:]][mask2d]))

        r_arcsec = row['radius']*u.arcsec
        reff = (r_arcsec*(8.5*u.kpc)).to(u.pc, u.dimensionless_angles())
        mass = ((10**logh2column*u.cm**-2)*np.pi*reff**2*2.8*constants.m_p).to(u.M_sun)
        density = (mass/(4/3.*np.pi*reff**3)/constants.m_p/2.8).to(u.cm**-3)

        columns['reff'].append(reff.value)
        columns['dustmass'].append(mass.value)
        columns['dustmindens'].append(density.value)
        mindens = np.log10(density.value)
        if mindens < 3:
            mindens = 3

        if (r321303 < 0 or np.isnan(r321303)) and line != '321':
            raise ValueError("Ratio <0: This can't happen any more because "
                             "if either num/denom is <0, an exception is "
                             "raised earlier")
            #for k in columns:
            #    if k not in obs_keys:
            #        columns[k].append(np.nan)
        elif (r321303 < 0 or np.isnan(r321303)) and line == '321':
            for k in keys:
                columns[k].append(np.nan)
        else:
            # Replace negatives for fitting
            if Smean321 <= 0:
                Smean321 = error
            mf.set_constraints(ratio321303=r321303, eratio321303=er321303,
                               #ratio321322=ratio2, eratio321322=eratio2,
                               logh2column=logh2column, elogh2column=elogh2column,
                               logabundance=logabundance, elogabundance=elogabundance,
                               taline303=Smean303, etaline303=error,
                               taline321=Smean321, etaline321=error,
                               mindens=mindens,
                               linewidth=10)
            row_data = mf.get_parconstraints()
            row_data['ratio321303'] = r321303
            row_data['eratio321303'] = er321303

            for k in row_data:
                columns[k].append(row_data[k])

            # Exclude bad velocities from cubes
            if row['v_cen'] < -80e3 or row['v_cen'] > 180e3:
                # Skip: there is no real structure down here
                nbad += 1
                is_bad = True
            else:
                is_bad = False
                tcubedata[dend_obj_mask.include()] = row_data['expected_temperature']
                if structure.is_leaf:
                    tcubeleafdata[dend_obj_mask.include()] = row_data['expected_temperature']

            columns['bad'].append(is_bad)

            width = row['v_rms']*u.km/u.s
            lengthscale = reff

            #REMOVED in favor of despotic version done in dendrograms.py
            # we use the analytic version here; the despotic version is
            # computed elsewhere (with appropriate gcor factors)
            #columns['tkin_turb'].append(heating.tkin_all(10**row_data['density_chi2']*u.cm**-3,
            #                                             width,
            #                                             lengthscale,
            #                                             width/lengthscale,
            #                                             columns['higaldusttem'][-1]*u.K,
            #                                             crir=0./u.s))

        if len(set(len(c) for k,c in columns.items())) != 1:
            print("Columns are different lengths.  This is not allowed.")
            import ipdb; ipdb.set_trace()

        for c in columns:
            assert len(columns[c]) == ii+1

        if plot_some and not is_bad and (ii-nbad % 100 == 0 or ii-nbad < 50):
            try:
                log.info("T: [{tmin1sig_chi2:7.2f},{expected_temperature:7.2f},{tmax1sig_chi2:7.2f}]"
                         "  R={ratio321303:8.4f}+/-{eratio321303:8.4f}"
                         "  Smean303={Smean303:8.4f} +/- {e303:8.4f}"
                         "  Stot303={Stot303:8.2e}  npix={npix:6d}"
                         .format(Smean303=Smean303, Stot303=Stot303,
                                 npix=npix, e303=error, **row_data))

                pl.figure(1)
                pl.clf()
                mf.denstemplot()
                pl.savefig(fpath("dendrotem/diagnostics/{0}_{1}.png".format(suffix,ii)))
                pl.figure(2).clf()
                mf.parplot1d_all(levels=[0.68268949213708585])
                pl.savefig(fpath("dendrotem/diagnostics/1dplot{0}_{1}.png".format(suffix,ii)))
                pl.draw()
                pl.show()
            except Exception as ex:
                print ex
                pass
        else:
            pb.update(ii+1)

        if last_index is not None and ii >= last_index:
            break

    if last_index is not None:
        catalog = catalog[:last_index+1]

    for k in columns:
        if k not in catalog.keys():
            catalog.add_column(table.Column(name=k, data=columns[k]))

    for mid,lo,hi,letter in (('expected_temperature','tmin1sig_chi2','tmax1sig_chi2','t'),
                             ('expected_density','dmin1sig_chi2','dmax1sig_chi2','d'),
                             ('expected_column','cmin1sig_chi2','cmax1sig_chi2','c')):
        catalog.add_column(table.Column(name='elo_'+letter,
                                        data=catalog[mid]-catalog[lo]))
        catalog.add_column(table.Column(name='ehi_'+letter,
                                        data=catalog[hi]-catalog[mid]))

    if write:
        catalog.write(tpath('PPV_H2CO_Temperature{0}.ipac'.format(suffix)), format='ascii.ipac')

    # Note that there are overlaps in the catalog, which means that ORDER MATTERS
    # in the above loop.  I haven't yet checked whether large scale overwrites
    # small or vice-versa; it may be that both views of the data are interesting.
    tcube = SpectralCube(data=tcubedata, wcs=cube303.wcs,
                         mask=cube303.mask, meta={'unit':'K'},
                         header=cube303.header,
                        )
    tcubeleaf = SpectralCube(data=tcubeleafdata, wcs=cube303.wcs,
                         mask=cube303.mask, meta={'unit':'K'},
                         header=cube303.header,
                        )

    if write:
        log.info("Writing TemperatureCube")
        outpath = 'TemperatureCube_DendrogramObjects{0}.fits'
        tcube.write(hpath(outpath.format(suffix)),
                    overwrite=True)

        outpath_leaf = 'TemperatureCube_DendrogramObjects{0}_leaves.fits'
        tcubeleaf.write(hpath(outpath_leaf.format(suffix)),
                    overwrite=True)


    return catalog, tcube
示例#37
0
print("Total flux: {0}".format(total_signal))
print("Total mass(20K): {0}".format(
    total_signal * masscalc.mass_conversion_factor() * u.M_sun / u.Jy))
print("Threshold column (20K): {0:e}".format(threshold_column))
print("Threshold density (20K): {0:e}".format(threshold_density))
flux_of_filament = 132 * u.Jy / u.beam / ppbeam
print("Total *filament* mass(20K): {0}".format(
    flux_of_filament * masscalc.mass_conversion_factor() * u.M_sun / u.Jy))
print("Total *filament* mass(100K): {0}".format(
    flux_of_filament * masscalc.mass_conversion_factor(TK=100) * u.M_sun /
    u.Jy))
print("Filament line mass: {0}".format(
    flux_of_filament * masscalc.mass_conversion_factor() * u.M_sun / u.Jy /
    (0.0027 * u.deg * masscalc.distance).to(u.pc, u.dimensionless_angles())))

dendro_merge = Table.read(paths.tpath('dendro_merge_continuum_and_line.ipac'),
                          format='ascii.ipac')
corelike = dendro_merge['corelike'] == 'True'
dendro_protostars_pt2 = dendro_merge['cont_flux0p2arcsec'].sum() * u.Jy
print("Total protostar flux (0.2): {0}".format(dendro_protostars_pt2))
print("Total protostar flux (peak): {0}".format(
    dendro_merge['peak_cont_flux'].sum() * u.Jy))
total_minus_protostars = total_signal - dendro_protostars_pt2
print("Total recovered flux minus protostars: {0}".format(
    total_minus_protostars))
print("Total mass minus protostars (20K): {0}".format(
    total_minus_protostars * masscalc.mass_conversion_factor() * u.M_sun /
    u.Jy))

# determine BGPS total mass
regions = pyregion.open(paths.rpath("12m_pointings.reg"))
示例#38
0
                          unit=unit)
    tbl.add_column(column)
 
# sort such that e10 comes after e9
tbl = tbl[natsort.index_natsorted(tbl['ObjectName'])]

detection_note = ['-' if name in detections else
                  'weak' if name in weakdetections else
                  'none'
                  for name in tbl['ObjectName']]
tbl.add_column(table.Column(data=detection_note, name='DetectionStatus'))

ok = np.array([row['ObjectName'] in detections+weakdetections
               for row in tbl])

tbl[ok].write(paths.tpath('H77a_spectral_fits.ipac'), format='ascii.ipac')

for old,new in [('ObjectName','Object Name'),
                ('H77a_amplitude', 'Amplitude',),
                ('eH77a_amplitude','$E$(Amplitude)',),
                ('H77a_velocity',  '$V_{LSR}$',),
                ('eH77a_velocity', '$E(V_{LSR})$',),
                ('H77a_width',     '$\sigma_V$',),
                ('eH77a_width',    '$E(\sigma_V)$'),
                ('DetectionStatus', 'Detection Status'),
               ]:
    tbl.rename_column(old, new)

for row in tbl:
    if "_" in row['Object Name']:
        row['Object Name'] = row['Object Name'].replace("_","\_")
示例#39
0
    kcl35 = Vamdc.query_molecule('KCl-35')
    rt35 = kcl35.data['RadiativeTransitions']
    frqs = u.Quantity([
        (float(rt35[key].FrequencyValue) * u.MHz).to(u.GHz, u.spectral())
        for key in rt35
    ])

    upperStateRefs = [rt35[key].UpperStateRef for key in rt35]
    degeneracies = [
        int(kcl35.data['States'][upperStateRef].TotalStatisticalWeight)
        for upperStateRef in upperStateRefs
    ]
    einsteinAij = u.Quantity(
        [float(rt35[key].TransitionProbabilityA) for key in rt35], 1 / u.s)

    tbl = table.Table.read(paths.tpath('fitted_stacked_lines.txt'),
                           format='ascii.fixed_width')

    kcl35mask = np.array([
        (not hasattr(row['Species'], 'mask'))
        and ('KCl' == row['Species'][:3] or '39K-35Cl' in row['Species'])
        for row in tbl
    ])

    bad = ((tbl['Line Name'] == 'KClv=4_13-12') |
           (tbl['Line Name'] == 'KClv=6_31-30') |
           (tbl['Line Name'] == 'KClv=8_27-26'))

    print("KCl: {0} in-band, {1} detected".format(kcl35mask.sum(),
                                                  (kcl35mask & (~bad)).sum()))
import radio_beam
import FITS_tools
import pyregion
try:
    from paths import tpath
except ImportError:
    tpath = lambda x: x

if os.path.exists('full_W51_7m12m_spw0_lines.fits'):
    tmplt = "full_W51_7m12m_spw{0}_lines.fits"
    suffix = "_7m12m"
else:
    tmplt = "full_W51_spw{0}_lines.fits"
    suffix = ''

pruned_ppcat = Table.read(tpath("dendrogram_continuum_catalog.ipac"),
                          format='ascii.ipac')
#dendromask = fits.open('dendrograms_min1mJy_diff1mJy_mask_pruned.fits')

for spw in (0,1,2,3):
    cube = SpectralCube.read(tmplt.format(spw))
    print(cube)

    #mask_reproj = FITS_tools.hcongrid.hastrom(dendromask[0].data.astype('float'),
    #                                          dendromask[0].header,
    #                                          FITS_tools.strip_headers.flatten_header(cube.header))
    #rmask = np.round(mask_reproj.data).astype('int')

    for row in pruned_ppcat:
        name = row['_idx']
        print("Extracting {0} from {1}".format(name, spw))
示例#41
0
import latex_info

# Filter out the high-v lines; they result in confusion in some cases (there
# are some v=10 lines really close to v=8 lines...)
salt_tables = [KCl, K37Cl, K41Cl, NaCl, Na37Cl, K41Cl37]
salt_tables = [tbl[tbl['vu'] < 9] for tbl in salt_tables]

dv = 15 * u.km / u.s
v = 5.5 * u.km / u.s
dv_linesearch = 5.0 * u.km / u.s

linefits = {}

chem_re = "KCl|NaCl|K37Cl|Na37Cl"

detection_table = Table.read(paths.tpath('salts_in_band.ipac'),
                             format='ascii.ipac')
nondetections = (detection_table['Flag'] == '-n') | (detection_table['Flag']
                                                     == 'cn')
detection_table = detection_table[~nondetections]

if 'doplot' not in locals():
    doplot = False

if doplot:
    pl.figure(0).clf()

for spw in (0, 1, 2, 3):
    for band in ('B3', 'B6', 'B7.lb'):
        fn = paths.dpath(
            'stacked_spectra/OrionSourceI_{band}_spw{0}_robust0.5.fits'.format(
示例#42
0
        "H2CO_321220_to_303202_cube_bl.fits",
        "H2CO_321220_to_303202_cube_smooth_bl.fits",
        "APEX_H2CO_303_202_bl.fits",
        "APEX_H2CO_321_220_bl.fits",
        "APEX_H2CO_322_221_bl.fits",
    )
] + [
    mpath(x) for x in (
        "APEX_13CO_2014_merge.fits",
        "APEX_C18O_2014_merge.fits",
        "APEX_H2CO_merge_high_plait_all.fits",
    )
] + [molpath(x) for x in ("APEX_SiO_54_bl.fits", )]

dendrograms = [hpath(x) for x in ("DendroMask_H2CO303202.hdf5", )] + [
    tpath(x) for x in (
        "fitted_line_parameters_Chi2Constraints.ipac",
        "PPV_H2CO_Temperature.ipac",
    )
]

if not os.path.isdir('cds'):
    os.mkdir('cds')
if not os.path.isdir('cds/integrated'):
    os.mkdir('cds/integrated')
if not os.path.isdir('cds/cubes'):
    os.mkdir('cds/cubes')
if not os.path.isdir('cds/catalogs'):
    os.mkdir('cds/catalogs')

for fn in integrated_files:
for ii, xx in enumerate(data['Dec']):
    data['Dec'][ii] = xx.replace('–', '-')

tbl = Table(data=[
    Column(data=data[colname], name=colname, unit=None or unit)
    for colname, unit in zip(colnames, units)
])
tbl.rename_column('log()', 'log(Q_lyc)')
tbl.rename_column('robs', 'tmp')
tbl.rename_column('ne', 'robs')
tbl.rename_column('tmp', 'ne')
tbl['ne'].unit = 1e4 * u.cm**-3
tbl['robs'].unit = 1e3 * u.au

tbl.write(paths.tpath("Schmiedeke2016_HIIregions_tableB1.txt"),
          format='ascii.fixed_width',
          overwrite=True)

reglist = [
    regions.CircleSkyRegion(
        coordinates.SkyCoord(row['RA'],
                             row['Dec'],
                             frame='fk5',
                             unit=(u.hour, u.deg)),
        radius=(u.Quantity(float(row['robs']) * 1000, u.au) /
                (8.5 * u.kpc)).to(u.arcsec, u.dimensionless_angles()),
        meta={'text': row['ID']},
        visual={'name': row['ID']},
    ) for row in tbl if row['ID']
]
示例#44
0
            'alpha',
            'alphaerror',
            'npix',
            'beam_area',
            'bgmad',
            'color',
            'peak_mass_20K',
            'peak_col_20K',
            'peak_mass_40K',
            'peak_col_40K',
            'peak_90GHz',
            'sum_90GHz',
            'bgmad_90GHz',
            'peak_100GHz',
            'sum_100GHz',
            'bgmad_100GHz',
        ]
    ])

    peak_brightness = (tbl['peak'] * u.beam).to(
        u.K,
        u.brightness_temperature(u.Quantity(tbl['beam_area']),
                                 masscalc.centerfreq))
    tbl.add_column(Column(data=peak_brightness, name='peak_K', unit=u.K))

    tbl.sort('peak_mass_40K')
    tbl = tbl[::-1]
    tbl.write(paths.tpath("continuum_photometry.ipac"),
              format='ascii.ipac',
              overwrite=True)
示例#45
0
    newcols = []
    for col in t.columns.values():
        if col.dtype.str.endswith('S5'):
            falses = col == 'False'
            trues = col == 'True'
            if np.all(falses | trues):
                col = t.ColumnClass(trues, name=col.name)
        newcols.append(col)
    return Table(newcols)


dend_sm = dendsm

try:
    catalog = fix_logical(
        Table.read(tpath('PPV_H2CO_Temperature.ipac'),
                   format='ascii.ipac',
                   guess=False))
    catalog_sm = fix_logical(
        Table.read(tpath('PPV_H2CO_Temperature_smooth.ipac'),
                   format='ascii.ipac',
                   guess=False))
    catalogsm = catalog_sm

except IOError:
    warnings.warn("Need to run dendro_temperature:do_dendro_temperatures_both"
                  " to get the PPV H2CO catalogs first")

#try:
#    catalog321 = Table.read(hpath('PPV_H2CO_Temperature_321selected.ipac'),
#                            format='ascii.ipac', guess=False)
示例#46
0
import numpy as np
from astropy.table import Table
import paths
from latex_info import latexdict, exp_to_tex, format_float
import natsort

tbl = Table.read('../tables/obs_meta.tbl', format='ascii', delimiter="|")

tbl = tbl[natsort.index_natsorted(tbl['Date'])]

latexdict['header_start'] = '\label{tab:obs_meta}'
latexdict['caption'] = 'Observation Metadata'
latexdict['tablefoot'] = ('')
latexdict['col_align'] = 'l' * 8
#latexdict['tabletype'] = 'longtable'
#latexdict['tabulartype'] = 'longtable'
tbl.write(paths.tpath('obs_meta.tex'),
          format='ascii.latex',
          latexdict=latexdict,
          formats={},
          overwrite=True)
示例#47
0
import paths
import numpy as np
from astropy.table import Table, Column
from astropy import coordinates
from astropy import units as u
from latex_info import (latexdict, format_float, round_to_n, rounded,
                        rounded_arr, strip_trailing_zeros, exp_to_tex)
from astropy.io import fits
from astropy import wcs

latexdict = latexdict.copy()

orig_cont_tbl = Table.read(paths.tpath("concatenated_catalog.ipac"),
                           format='ascii.ipac')
cont_tbl = Table.read(paths.tpath("concatenated_catalog.ipac"),
                      format='ascii.ipac')
rejected = cont_tbl['rejected']

description = {
    '_idx': 'Source ID number',
    'MUSTANG_10as_sum': 'MUSTANG aperture flux within a 10" aperture',
    'MUSTANG_15as_sum': 'MUSTANG aperture flux within a 15" aperture',
    'x_cen': 'Dendrogram moment-1 Galactic longitude',
    'y_cen': 'Dendrogram moment-1 Galactic latitude',
    'MUSTANG_dend_flux': 'Dendrogram contour-integrated intensity',
    'MUSTANG_background_median':
    'Median background intensity in 15"-20" annulus',
    'amplitude': 'Gaussian fit amplitude',
    'center_x': 'Gaussian fit Galactic longitude',
    'center_y': 'Gaussian fit Galactic latitude',
    'fwhm_major': 'Gaussian fit FWHM along the major axis',
示例#48
0
        ax.yaxis.set_ticklabels([])
        ax.yaxis.set_label("")
        if ii < plotnum-7:
            ax.xaxis.set_ticklabels([])
            ax.xaxis.set_label("")

    pl.savefig(paths.fpath('spectral_fits/{0}_linefits.png'.format(name)),
               bbox_inches='tight', bbox_extra_artists=[])

    pl.figure(2).clf()
    widths = line_table['{0}FittedWidth'.format(name)]
    ewidths = line_table['{0}FittedWidthError'.format(name)]
    labels = line_table['Species']
    inds = np.argsort(widths)
    mask = (widths[inds]>0) & (widths[inds]<5) & (ewidths[inds] < widths[inds]) & (ewidths[inds] < 5)
    pl.errorbar(x=np.arange(mask.sum()),
                y=widths[inds][mask],
                yerr=ewidths[inds][mask],
                linestyle='none',
                color='k')
    ax = pl.gca()
    ax.set_xticks(np.arange(mask.sum()))
    ax.set_xticklabels(labels[inds][mask], rotation='vertical')
    ax.set_xlim(-1, mask.sum()+1)
    pl.savefig(paths.fpath('spectral_fits/{0}_linewidths.png'.format(name)),
               bbox_inches='tight', bbox_extra_artists=[])


    line_table.write(paths.tpath('spectral_lines_and_fits.csv'),
                     overwrite=True)
        results_inv['name'][k] = k
        columns['name'].append(k)
        for kk,vv in v.items():
            if kk in results_inv:
                results_inv[kk][k] = vv
                columns[kk].append(vv)
            else:
                results_inv[kk] = {k:vv}
                columns[kk] = [vv]

    for c in columns:
        if c in units:
            columns[c] = u.Quantity(columns[c], units[c])

    tbl = Table([Column(data=columns[k],
                        name=k)
                 for k in ['name', 'RA', 'Dec', 'peak', 'sum', 'npix', 'beam_area',
                           'bgmad', 
                           'peak_90GHz', 'sum_90GHz', 'bgmad_90GHz',
                           'peak_100GHz', 'sum_100GHz', 'bgmad_100GHz',
                           'peak_mass_20K', 'peak_col_20K']])

    peak_brightness = (tbl['peak']*u.beam).to(u.K,
                                              u.brightness_temperature(tbl['beam_area'],
                                                                       masscalc.centerfreq))
    tbl.add_column(Column(data=peak_brightness, name='peak_K', unit=u.K))

    tbl.sort('peak_mass_20K')
    tbl.write(paths.tpath("continuum_photometry.ipac"), format='ascii.ipac',
              overwrite=True)
示例#50
0
import numpy as np
import paths
from astropy import coordinates
from astropy.table import Table

core_phot_tbl = Table.read(
    paths.tpath("continuum_photometry_withSIMBAD_andclusters.ipac"),
    format='ascii.ipac')
hiis = np.array(['HII' in row['Classification'] for row in core_phot_tbl],
                dtype='bool')
strong = np.array(['S' in row['Classification'] for row in core_phot_tbl],
                  dtype='bool')
weak = np.array(['W' == row['Classification'][0] for row in core_phot_tbl],
                dtype='bool')
xray = np.array(['X' in row['Classification'] for row in core_phot_tbl],
                dtype='bool')
methanolmaser = np.array(
    ['M' in row['Classification'] for row in core_phot_tbl], dtype='bool')
watermaser = np.array(
    ['W' == row['Classification'][5] for row in core_phot_tbl], dtype='bool')
maser = methanolmaser | watermaser
print(
    "Found {0} HII regions, {1} strong sources, {2} weak sources, {3} X-ray sources, "
    "{4} methanol masers, and {5} water masers (total {6} masers)".format(
        hiis.sum(), strong.sum(), weak.sum(), xray.sum(), methanolmaser.sum(),
        watermaser.sum(), maser.sum()))
assert all(weak == ~strong)
not_measured = core_phot_tbl['peak'] == 0.0
measured = ~not_measured
cores = coordinates.SkyCoord(core_phot_tbl['RA'],
                             core_phot_tbl['Dec'],
示例#51
0
    for par in sp.specfit.parinfo.keys()
]
ra, dec = (table.Column(name='RA',
                        data=u.Quantity([coords[key].ra for key in names])),
           table.Column(name='Dec',
                        data=u.Quantity([coords[key].dec for key in names])))

allcols = [table.Column(data=names, name='Name'), ra, dec
           ] + [z for x, y in zip(columns, errcolumns) for z in (x, y)]
tbl = table.Table(allcols)

snr = tbl['AMPLITUDE0'] / tbl['e_AMPLITUDE0']
tbl.add_column(table.Column(name='SNR41', data=snr))
ok = snr > 3

tbl[ok].write(paths.tpath('H41a_fits.ipac'),
              format='ascii.ipac',
              overwrite=True)
for cn in [xx.name for xx in columns] + [xx.name for xx in errcolumns]:
    tbl[~ok][cn] = np.nan
    tbl[cn][~ok] = np.nan

print(tbl['Name', 'SNR41'][~ok])

center = coordinates.SkyCoord('17:47:20.174',
                              '-28:23:04.233',
                              frame='fk5',
                              unit=(u.hour, u.deg))

depree = table.Table.read(paths.tpath('DePree2011.txt'),
                          format='ascii.fixed_width',
    colnames = {'name'} # set
    for k,v in all_results.items():
        results_inv['name'][k] = k
        columns['name'].append(k)
        for kk,vv in v.items():
            colnames.add(kk)
            if kk in results_inv:
                results_inv[kk][k] = vv
                columns[kk].append(vv)
            else:
                results_inv[kk] = {k:vv}
                columns[kk] = [vv]

    for c in columns:
        umatch = [k for k in units if k in c]
        if len(umatch) >= 1:
            cn = max(umatch, key=len)
            columns[c] = u.Quantity(columns[c], units[cn])

    tbl = Table([Column(data=columns[k],
                        name=k)
                 for k in sorted(colnames)])

    tbl.write(paths.tpath("line_photometry.csv"), format='ascii.csv',
              overwrite=True)
    tbl.write(paths.tpath("line_photometry.tab"), format='ascii.fixed_width',
              delimiter='|',
              overwrite=True)
    tbl.write(paths.tpath("line_photometry.ipac"), format='ascii.ipac',
              overwrite=True)
import numpy as np
from astropy.table import Table, Column
from astropy import coordinates
from astropy import units as u
from latex_info import (latexdict, format_float, round_to_n,
                        strip_trailing_zeros, exp_to_tex)
from astropy.io import fits
from astropy import wcs
from files import contfilename

latexdict = latexdict.copy()

sgrb2contfile = fits.open(contfilename)

orig_cont_tbl = Table.read(
    paths.tpath("continuum_photometry_withSIMBAD_andclusters.ipac"),
    format='ascii.ipac')
cont_tbl = Table.read(
    paths.tpath("continuum_photometry_withSIMBAD_andclusters.ipac"),
    format='ascii.ipac')

for row in cont_tbl:
    row['name'] = row['name'].replace("core_", "").replace("_", " ")

cont_tbl.rename_column('name', 'ID')

cont_tbl.add_column(
    Column(name='$S_{\\nu,max}$', data=cont_tbl['peak'].to(u.mJy / u.beam)))
cont_tbl.remove_column('peak')
cont_tbl.add_column(Column(name='$T_{B,max}$',
                           data=cont_tbl['peak_K'].to(u.K)))
            ax.set_ylabel("$T_B$ [K]")

        if title is not None:
            pl.subplot(7,1,1).set_title(title)

        if figname is not None:
            pl.savefig(paths.fpath(figname), dpi=300, bbox_inches='tight',
                       bbox_extra_artists=[])

if __name__ == "__main__":

    import glob
    import radio_beam
    from astropy.table import Table

    myvtbl = Table.read(paths.tpath('core_velocities.txt'),
                        # write as ascii.fixed_width
                        format='ascii.fixed_width', delimiter='|')

    line_table = Table.read(paths.apath('full_line_table.csv'))
    all_line_ids = {"{0}_{1}".format(row['Species'], row['Resolved QNs']):
                    (row['Freq-GHz'] if row['Freq-GHz']
                     else row['Meas Freq-GHz'])*u.GHz
                    for row in line_table}
    all_line_ids.update(line_ids)

    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:
                                               tbl['Frequency'])
                           ],
                      name='Jy-Kelvin'))
tbl.add_column(Column(data=((tbl['RMS']*u.beam).to(u.Jy).value*tbl['Jy-Kelvin'])*u.K,
                      name='RMS$_K$'), index=4)

tbl.sort(['Frequency'])
latexdict['header_start'] = '\label{tab:cubes}'
latexdict['caption'] = 'Spectral Cubes'
latexdict['tablefoot'] = ('\par\nJy-Kelvin gives the conversion factor from Jy '
                          'to Kelvin given the synthesized beam size and '
                          'observation frequency.')
latexdict['col_align'] = 'l'*len(tbl.columns)
#latexdict['tabletype'] = 'longtable'
#latexdict['tabulartype'] = 'longtable'
def round_to_n(x, n):
    return round(x, -int(np.floor(np.log10(x))) + (n - 1))


tbl.write(paths.tpath('cubes.tex'), format='ascii.latex',
          latexdict=latexdict,
          formats={'BMAJ': lambda x: '{0:0.2f}'.format(x),
                   'BMIN': lambda x: '{0:0.2f}'.format(x),
                   'BPA':  lambda x: '{0}'.format(int(x)),
                   'RMS': lambda x: '{0:0.2f}'.format(x),
                   'RMS$_K$': format_float,
                   'Channel Width': lambda x: '{0:0.2f}'.format(x),
                   'Frequency': lambda x: '{0:0.6f}'.format(x),
                   'Jy-Kelvin':  format_float,
                  },)
import contextlib

devnull = open(os.devnull, 'w')

log.setLevel('CRITICAL')

pl.style.use('classic')
pl.matplotlib.rc_file('pubfiguresrc')
pl.mpl.rcParams['font.size'] = 14.0
pl.mpl.rcParams['axes.titlesize'] = 16.0
pl.mpl.rcParams['axes.labelsize'] = 15.0
pl.mpl.rcParams['axes.prop_cycle'] = matplotlib.cycler(
    'color', ('338ADD', '9A44B6', 'A60628', '467821', 'CF4457', '188487',
              'E24A33', 'b', 'r', 'g', 'm', 'k'))

core_velo_tbl = Table.read(paths.tpath("core_velocities.ipac"),
                           format="ascii.ipac")
core_phot_tbl = Table.read(paths.tpath("continuum_photometry.ipac"),
                           format='ascii.ipac')
cores_merge = Table.read(paths.tpath('core_continuum_and_line.ipac'),
                         format='ascii.ipac')

beam_area = cores_merge['beam_area']
jy_to_k = (1 * u.Jy).to(
    u.K, u.brightness_temperature(u.Quantity(beam_area, u.sr),
                                  226 * u.GHz)).mean()

fig1 = pl.figure(1)
fig1.clf()
ax1 = fig1.gca()
示例#57
0
def mvir(radius, vdisp_1d, prefactor_eta=3.39):
    """
    Compute the virial mass given the 1-D velocity dispersion and the half-mass radius

    This is a simplified virial mass with
    M = sigma_3d**2 * radius / G
    and sigma_3d = sqrt(3) * sigma_1d

    prefactor_eta = 6*16/(3*pi)/3 = 3.39 for a Plummer sphere for stars
    prefactor_eta = 1 for r^-2 cloud (MacLaren 1988)
    prefactor_eta = 5/3 for rho=const cloud (MacLaren 1988)
    """
    return prefactor_eta * ((3 * vdisp_1d**2) * radius / constants.G).to(u.M_sun)

tbl22 = table.Table.read(paths.tpath('H2CO22_emission_spectral_fits.ecsv'), format='ascii.ecsv')
tbl77 = table.Table.read(paths.tpath('H77a_spectral_fits.ipac'), format='ascii.ipac')

cluster_sources = ['e8mol', 'e10mol', 'e1', 'e2', 'e3', 'e4']
cluster_sources_optimistic = ['e8mol', 'e10mol', 'e1', 'e2', 'e3', 'e4', 'e9',]
e1cluster = ['e8mol', 'e10mol', 'e1', 'e3', 'e4',] # e9 is 'optimistic'

velocities = ([row['$V_{LSR}$'] for row in tbl22 if row['Object Name'] in cluster_sources] +
              [row['H77a_velocity'] for row in tbl77 if row['ObjectName'] in cluster_sources])
print("Mean velocity including only solid detections: {0}".format(np.mean(velocities)))
print("Velocity dispersion including only solid detections: {0}".format(np.std(velocities)))
print("Virial mass in e1e2 using R=0.16 pc from spanning_tree: {0}".format(mvir(0.16*u.pc, np.std(velocities)*u.km/u.s)))
density_e1e2 = (mvir(0.16*u.pc, np.std(velocities)*u.km/u.s)/(2.8*u.Da)/(4/3.*np.pi*(0.16*u.pc)**3)).to(u.cm**-3)
print("Density from that mass: 10^{0} = {1}x10^6".format(np.log10(density_e1e2.value), density_e1e2/1e6))
velocities_optimistic = ([row['$V_{LSR}$'] for row in tbl22 if row['Object Name'] in cluster_sources_optimistic] +
                         [row['H77a_velocity'] for row in tbl77 if row['ObjectName'] in cluster_sources_optimistic])