示例#1
0
def test_eriks_idl(testspec_idl_str, tex, tkin, plot=False):
    idl_test_xarr = np.array(xarr_idl_str.split(), dtype='float')
    idl_test_spectrum = np.array(testspec_idl_str.split(), dtype='float')

    refX = 23.6944955e9  # from nh3model.pro
    refX = 23.694506e9  # from modelspec.pro

    xarr11 = pyspeckit.units.SpectroscopicAxis(np.arange(-30, 30, 0.4),
                                               unit='km/s',
                                               refX=refX,
                                               refX_unit='Hz',
                                               frame='LSRK',
                                               xtype='Frequency')

    # The two arrays are shifted in frequency because nh3model.pro converts to
    # frequency with a different reference; the reference frequency is not centered
    # on any of the individual lines
    #print(np.array(xarr11.as_unit('Hz')) - idl_test_xarr)

    ps_spectrum = ammonia.ammonia(
        xarr11,
        tkin=tkin,
        tex=tex,
        ntot=14,
        width=1,
        xoff_v=0.0,
        fortho=0.5,
    )

    absfracdiff = np.abs((idl_test_spectrum - ps_spectrum) /
                         idl_test_spectrum * (np.abs(idl_test_spectrum) > 0))

    if plot:
        import pylab as pl
        fig1 = pl.figure(1)
        fig1.clf()
        ax1 = fig1.gca()
        ax1.plot(idl_test_xarr, idl_test_spectrum, label="IDL")
        ax1.plot(xarr11.as_unit('Hz'), ps_spectrum, label="pyspeckit")
        ax1.set_xlabel("Frequency (Hz)")
        ax1.set_ylabel("Test spectra")
        pl.legend(loc='best')

        fig2 = pl.figure(2)
        fig2.clf()
        ax2 = fig2.gca()
        ax2.plot(xarr11,
                 np.abs(idl_test_spectrum - ps_spectrum) / idl_test_spectrum)
        ax2.set_xlabel("Frequency (Hz)")
        ax2.set_ylabel("(IDL-pyspeckit)/IDL")

        pl.draw()
        pl.show()

    assert np.nanmax(absfracdiff) < 0.01

    return absfracdiff
示例#2
0
def test_eriks_idl(testspec_idl_str, tex, tkin, plot=False):
    idl_test_xarr = np.array(xarr_idl_str.split(), dtype='float')
    idl_test_spectrum = np.array(testspec_idl_str.split(), dtype='float')

    refX = 23.6944955e9 # from nh3model.pro
    refX = 23.694506e9 # from modelspec.pro

    xarr11 = pyspeckit.units.SpectroscopicAxis(np.arange(-30,30,0.4),
                                               unit='km/s', refX=refX,
                                               refX_unit='Hz', frame='LSRK',
                                               xtype='Frequency')

    # The two arrays are shifted in frequency because nh3model.pro converts to
    # frequency with a different reference; the reference frequency is not centered
    # on any of the individual lines
    #print(np.array(xarr11.as_unit('Hz')) - idl_test_xarr)

    ps_spectrum = ammonia.ammonia(xarr11, tkin=tkin, tex=tex, ntot=14, width=1,
                                  xoff_v=0.0, fortho=0.5, )

    absfracdiff = np.abs((idl_test_spectrum - ps_spectrum)/idl_test_spectrum * (np.abs(idl_test_spectrum) > 0))

    if plot:
        import pylab as pl
        fig1 = pl.figure(1)
        fig1.clf()
        ax1 = fig1.gca()
        ax1.plot(idl_test_xarr, idl_test_spectrum, label="IDL")
        ax1.plot(xarr11.as_unit('Hz'), ps_spectrum, label="pyspeckit")
        ax1.set_xlabel("Frequency (Hz)")
        ax1.set_ylabel("Test spectra")
        pl.legend(loc='best')

        fig2 = pl.figure(2)
        fig2.clf()
        ax2 = fig2.gca()
        ax2.plot(xarr11, np.abs(idl_test_spectrum - ps_spectrum)/idl_test_spectrum)
        ax2.set_xlabel("Frequency (Hz)")
        ax2.set_ylabel("(IDL-pyspeckit)/IDL")

        pl.draw()
        pl.show()

    assert np.nanmax(absfracdiff) < 0.01

    return absfracdiff
# Note that they are converted to GHz first
xarr11 = SpectroscopicAxis(np.linspace(-30, 30, 100)*u.km/u.s,
                           velocity_convention='radio',
                           refX=freq_dict['oneone']).as_unit(u.GHz)
xarr22 = SpectroscopicAxis(np.linspace(-40, 40, 100)*u.km/u.s,
                           velocity_convention='radio',
                           refX=freq_dict['twotwo']).as_unit(u.GHz)
xarr33 = SpectroscopicAxis(np.linspace(-50, 50, 100)*u.km/u.s,
                           velocity_convention='radio',
                           refX=freq_dict['threethree']).as_unit(u.GHz)
# Merge the three X-axes into a single axis
xarr = SpectroscopicAxes([xarr11,xarr22,xarr33])

# Compute a synthetic model that is made of two temperature components with
# identical velocities
synthspec = (ammonia.ammonia(xarr, tkin=20, ntot=15, fortho=0.5, xoff_v=0.0,
                             width=1.0) +
             ammonia.ammonia(xarr, tkin=50, ntot=14, fortho=0.5, xoff_v=0.0,
                             width=1.0))

# Create the Spectrum object
spectrum = pyspeckit.Spectrum(xarr=xarr, data=synthspec)


# Step 2.  You have a spectrum.
# plot it
spectrum.plotter()

# Use the multi-tex/multi-tau model generator to build up a model function
# You can use any set of oneone, twotwo, ..., eighteight (no 9-9 or higher)
# This sets the number of parameters to be fit: 2+2*(n_transitions)
fitter = ammonia_hf.nh3_vtau_multimodel_generator(['oneone', 'twotwo',
示例#4
0
xarr11 = SpectroscopicAxis(np.linspace(-30, 30, 100) * u.km / u.s,
                           velocity_convention='radio',
                           refX=freq_dict['oneone']).as_unit(u.GHz)
xarr22 = SpectroscopicAxis(np.linspace(-40, 40, 100) * u.km / u.s,
                           velocity_convention='radio',
                           refX=freq_dict['twotwo']).as_unit(u.GHz)
xarr33 = SpectroscopicAxis(np.linspace(-50, 50, 100) * u.km / u.s,
                           velocity_convention='radio',
                           refX=freq_dict['threethree']).as_unit(u.GHz)
# Merge the three X-axes into a single axis
xarr = SpectroscopicAxes([xarr11, xarr22, xarr33])

# Compute a synthetic model that is made of two temperature components with
# identical velocities
synthspec = (
    ammonia.ammonia(xarr, tkin=20, ntot=15, fortho=0.5, xoff_v=0.0,
                    width=1.0) +
    ammonia.ammonia(xarr, tkin=50, ntot=14, fortho=0.5, xoff_v=0.0, width=1.0))

# Create the Spectrum object
spectrum = pyspeckit.Spectrum(xarr=xarr, data=synthspec)

# Step 2.  You have a spectrum.
# plot it
spectrum.plotter()

# Use the multi-tex/multi-tau model generator to build up a model function
# You can use any set of oneone, twotwo, ..., eighteight (no 9-9 or higher)
# This sets the number of parameters to be fit: 2+2*(n_transitions)
fitter = ammonia_hf.nh3_vtau_multimodel_generator(
    ['oneone', 'twotwo', 'threethree'])
oneonefreq = ammonia_constants.freq_dict['oneone']
twotwofreq = ammonia_constants.freq_dict['twotwo']
# create an axis that covers the 1-1 and 2-2 inversion lines
xaxis = pyspeckit.units.SpectroscopicAxis(np.linspace(
    oneonefreq * (1 - 50 / 3e5), twotwofreq * (1 + 50 / 3e5), 1000.),
                                          unit=u.Hz)
sigma = 2.
center = 0.
trot = 35.
ntot = 15.
# Adopting an NLTE model: T_ex < T_rot (this case is better for the default fitter)
# pyradex.Radex(species='p-nh3', column=10e14, collider_densities={'h2':10000}, temperature=35)()[8:10]
tex = {'oneone': 16.4, 'twotwo': 12.6}
synth_data = ammonia.ammonia(xaxis,
                             trot=trot,
                             tex=tex,
                             width=sigma,
                             xoff_v=center,
                             ntot=ntot)

# Add noise
stddev = 0.1
noise = np.random.randn(xaxis.size) * stddev
error = stddev * np.ones_like(synth_data)
data = noise + synth_data

# this will give a "blank header" warning, which is fine
sp = pyspeckit.Spectrum(data=data,
                        error=error,
                        xarr=xaxis,
                        xarrkwargs={'unit': 'km/s'},
                        unit=u.K)
示例#6
0
    tx = 7.5
    nt = 15
    sig = 0.5
np.seterr(all='ignore')
for tk in test_parameters['TKIN']:
    for txf in test_parameters['Tex_frac']:
        for nt in test_parameters['ntot']:
            for sig in test_parameters['width']:
#for tk, txf, nt, sig in (parlist):

                t0 = time.time()
                tx = max([txf*tk,3]) # tx can't be too close to T(CMB)

                ins.append([tk,tx,nt,sig])

                fake_spec = ammonia.ammonia(xarr, tkin=tk, tex=tx, ntot=nt, width=sig, xoff_v=0,
                        fortho=0.5)
                real_tau = ammonia.ammonia(xarr, tkin=tk, tex=tx, ntot=nt, width=sig, xoff_v=0,
                        fortho=0.5, return_tau=True)

                if fake_spec.max()*3 < noise:
                    noises.append(fake_spec.max()/3.)
                    fake_spec += np.random.randn(fake_spec.size) * fake_spec.max()/3.
                    signoise.append(3)
                else:
                    noises.append(noise)
                    signoise.append(fake_spec.max()/noise)
                    fake_spec += np.random.randn(fake_spec.size) * noise

                sp = pyspeckit.Spectrum(xarr=xarr, data=fake_spec, err=err,units='K', header=pyfits.Header({'BUNIT':'K'}))
                
                # sp.plotter()
示例#7
0
    limitedmin=[True,True,True,True,False,True]*2, quiet=False,
    show_components=True
    )
if True:
    figure(1); clf();
    sp.specfit.fullsizemodel()
    sp.xarr.convert_to_unit('GHz',frame='LSR')
    sp.plotter(axis=subplot(211),xmin=2.3689e1,xmax=2.3694e1)
    sp.specfit.plot_fit(show_components=True)
    sp.specfit.fullsizemodel()
    sp.plotter(axis=subplot(223),xmin=2.3717e1,xmax=2.3722e1)
    sp.specfit.plot_fit(show_components=True)
    sp.specfit.fullsizemodel()
    sp.plotter(axis=subplot(224),xmin=2.387013e1-5.4e-3,xmax=2.387013e1)
    sp.specfit.plot_fit(show_components=True)
    sp.specfit.annotate(labelspacing=0.05,prop={'size':'small','stretch':'extra-condensed'},frameon=False,)
    sp.plotter.figure.savefig(savedir+'nh3_ammonia_multifit_multipanel_zoom_basedon33.png')

from pyspeckit.spectrum.models import ammonia

taudict = ammonia.ammonia(sp.xarr, tkin=sp.specfit.parinfo.tkin0.value,
                          tex=sp.specfit.parinfo.tex0.value,
                          ntot=sp.specfit.parinfo.ntot0.value,
                          width=sp.specfit.parinfo.width0.value,
                          return_tau=True)

# Empirical result
assert 40 < taudict['oneone'] < 42

if interactive: raw_input('Press enter to end code')
xarr11 = SpectroscopicAxis(np.linspace(-30, 30, 100) * u.km / u.s,
                           velocity_convention='radio',
                           refX=freq_dict['oneone']).as_unit(u.GHz)
xarr22 = SpectroscopicAxis(np.linspace(-40, 40, 100) * u.km / u.s,
                           velocity_convention='radio',
                           refX=freq_dict['twotwo']).as_unit(u.GHz)
xarr33 = SpectroscopicAxis(np.linspace(-50, 50, 100) * u.km / u.s,
                           velocity_convention='radio',
                           refX=freq_dict['threethree']).as_unit(u.GHz)
# Merge the three X-axes into a single axis
xarr = SpectroscopicAxes([xarr11, xarr22, xarr33])

# Compute a synthetic model that is made of two temperature components with
# identical velocities
synthspec = (
    ammonia.ammonia(xarr, tkin=20, ntot=15, fortho=0.5, xoff_v=0.0,
                    width=1.0) +
    ammonia.ammonia(xarr, tkin=50, ntot=14, fortho=0.5, xoff_v=0.0, width=1.0))

# Create the Spectrum object
spectrum = pyspeckit.Spectrum(xarr=xarr, data=synthspec)

# Step 2.  You have a spectrum.
# plot it
spectrum.plotter()

# Use the multi-tex/multi-tau model generator to build up a model function
# You can use any set of oneone, twotwo, ..., eighteight (no 9-9 or higher)
# This sets the number of parameters to be fit: 2+2*(n_transitions)
fitter = ammonia_hf.nh3_vtau_multimodel_generator(
    ['oneone', 'twotwo', 'threethree'])
示例#9
0
                                                       oneonefreq*(1+50/3e5),
                                                       80.), unit=u.Hz,
                                           velocity_convention='radio',
                                           refX=oneonefreq*u.Hz)
xaxis2 = pyspeckit.units.SpectroscopicAxis(np.linspace(twotwofreq*(1-50/3e5),
                                                       twotwofreq*(1+50/3e5),
                                                       80.), unit=u.Hz,
                                           velocity_convention='radio',
                                           refX=twotwofreq*u.Hz)

sigma = 2.
center = 0.
trot = 35.
ntot = 15.5
tex = 35. # Adopting an LTE model
synth_data1 = ammonia.ammonia(xaxis1, trot=trot, tex=tex, width=sigma,
                              xoff_v=center, ntot=ntot)
synth_data2 = ammonia.ammonia(xaxis2, trot=trot, tex=tex, width=sigma,
                              xoff_v=center, ntot=ntot)

# Add noise
stddev = 0.4
noise = np.random.randn(xaxis1.size)*stddev
error = stddev*np.ones_like(synth_data1)
data1 = noise+synth_data1
noise = np.random.randn(xaxis2.size)*stddev
data2 = noise+synth_data2

# this will give a "blank header" warning, which is fine
sp1 = pyspeckit.Spectrum(data=data1, error=error, xarr=xaxis1,
                         xarrkwargs={'unit':'km/s', 'refX': oneonefreq*u.Hz,},
                         unit=u.K)
from __future__ import print_function
import pyspeckit
import numpy as np
from astropy import units as u

from pyspeckit.spectrum.models import ammonia

xarr = np.linspace(-40, 40, 300) * u.km/u.s
oneonemod = ammonia.ammonia(xarr.to(u.GHz, u.doppler_radio(ammonia.freq_dict['oneone']*u.Hz)),)
twotwomod = ammonia.ammonia(xarr.to(u.GHz, u.doppler_radio(ammonia.freq_dict['twotwo']*u.Hz)),)

sp11 = pyspeckit.Spectrum(xarr=xarr, data=oneonemod, unit=u.K,
                          xarrkwargs={'refX': ammonia.freq_dict['oneone']*u.Hz},
                          header={})
sp22 = pyspeckit.Spectrum(xarr=xarr, data=twotwomod, unit=u.K,
                          xarrkwargs={'refX': ammonia.freq_dict['twotwo']*u.Hz},
                          header={})


input_dict={'oneone':sp11, 'twotwo':sp22,}
spf, specout = pyspeckit.wrappers.fitnh3.fitnh3tkin(input_dict, dobaseline=False)
print(specout.specfit.modelpars)
print(specout.specfit.parinfo)

spf2, specout2 = pyspeckit.wrappers.fitnh3.fitnh3tkin(input_dict,
                                                      dobaseline=True,
                                                      baselinekwargs={'exclude':[-30,30]*u.km/u.s})
print(specout.specfit.modelpars)
print(specout.specfit.parinfo)
示例#11
0
from __future__ import print_function
import pyspeckit
import numpy as np
from astropy import units as u

from pyspeckit.spectrum.models import ammonia

xarr = np.linspace(-40, 40, 300) * u.km / u.s
oneonemod = ammonia.ammonia(
    xarr.to(u.GHz, u.doppler_radio(ammonia.freq_dict['oneone'] * u.Hz)), )
twotwomod = ammonia.ammonia(
    xarr.to(u.GHz, u.doppler_radio(ammonia.freq_dict['twotwo'] * u.Hz)), )

sp11 = pyspeckit.Spectrum(
    xarr=xarr,
    data=oneonemod,
    unit=u.K,
    xarrkwargs={'refX': ammonia.freq_dict['oneone'] * u.Hz},
    header={})
sp22 = pyspeckit.Spectrum(
    xarr=xarr,
    data=twotwomod,
    unit=u.K,
    xarrkwargs={'refX': ammonia.freq_dict['twotwo'] * u.Hz},
    header={})

input_dict = {
    'oneone': sp11,
    'twotwo': sp22,
}
spf, specout = pyspeckit.wrappers.fitnh3.fitnh3tkin(input_dict,
oneonefreq = ammonia_constants.freq_dict['oneone']
twotwofreq = ammonia_constants.freq_dict['twotwo']
# create an axis that covers the 1-1 and 2-2 inversion lines
xaxis = pyspeckit.units.SpectroscopicAxis(np.linspace(oneonefreq*(1-50/3e5),
                                                      twotwofreq*(1+50/3e5),
                                                      1000.),
                                          unit=u.Hz)
sigma = 2.
center = 0.
trot = 35.
ntot = 15.
# Adopting an NLTE model: T_ex < T_rot (this case is better for the default fitter)
# pyradex.Radex(species='p-nh3', column=10e14, collider_densities={'h2':10000}, temperature=35)()[8:10]
tex = {'oneone':16.4, 'twotwo':12.6}
synth_data = ammonia.ammonia(xaxis, trot=trot, tex=tex, width=sigma,
                             xoff_v=center, ntot=ntot)

# Add noise
stddev = 0.1
noise = np.random.randn(xaxis.size)*stddev
error = stddev*np.ones_like(synth_data)
data = noise+synth_data

# this will give a "blank header" warning, which is fine
sp = pyspeckit.Spectrum(data=data, error=error, xarr=xaxis,
                        xarrkwargs={'unit':'km/s'},
                        unit=u.K)

sp.plotter(figure=pl.figure(1), errstyle='fill')

# fit with some vague initial guesses and a fixed ortho/para