def gen_spec(model_params):
    """
    Generate a synthetic spectrum
    model_params = [Tkin, Tex, Ntot, width]
    """
    xarr11 = SpectroscopicAxis(np.linspace(-40, 40, 1000) * u.km / u.s,
                               velocity_convention='radio',
                               refX=freq_dict['oneone']).as_unit(u.GHz)
    xarr22 = SpectroscopicAxis(np.linspace(-40, 40, 1000) * u.km / u.s,
                               velocity_convention='radio',
                               refX=freq_dict['twotwo']).as_unit(u.GHz)
    xarr = SpectroscopicAxes([xarr11, xarr22])
    tkin = model_params[0]
    tex = model_params[1]
    ntot = model_params[2]
    width = model_params[3]
    fortho = 0.0
    synthspec = pyspeckit.spectrum.models.ammonia.cold_ammonia(xarr,
                                                               tkin=tkin,
                                                               tex=tex,
                                                               ntot=ntot,
                                                               width=width,
                                                               fortho=fortho)
    spectrum = pyspeckit.Spectrum(xarr=xarr, data=synthspec)
    return spectrum
Exemple #2
0
def toy_observation(snr=2,
                    debug=False,
                    seed=0,
                    v1=10,
                    v2=70,
                    nchan=1000,
                    truth_narrow=[4, 40, 1.0],
                    truth_wide=[2, 41, 3.0]):
    np.random.seed(seed)
    if debug:  # <CheatMode>
        log.setLevel('DEBUG')

    # initialize the spectral axis
    xunit, bunit = 'km/s', 'K'
    refX = 120 * u.GHz
    log.debug("Genarating a spactral axis instance from {}"
              " to {} {}".format(v1, v2, xunit))
    xarr = SpectroscopicAxis(np.linspace(v1, v2, nchan) * u.Unit(xunit),
                             refX=refX,
                             velocity_convention='radio')

    # generate a spectrum approximated by a gaussian
    log.debug("Gaussian parameters for the"
              " narrow component: {}".format(truth_narrow))
    log.debug("Gaussian parameters for the"
              " wide component: {}".format(truth_wide))
    true_data_narrow = gaussian(xarr, *truth_narrow)
    true_data_wide = gaussian(xarr, *truth_wide)

    true_total = true_data_narrow + true_data_wide
    signal_peak = true_total.max()
    log.debug("For a signal-to-noise ratio of {} the square root of noise"
              " variance is {:.2f} {}.".format(snr, signal_peak / snr, bunit))
    noise = np.random.normal(loc=0, scale=signal_peak / snr, size=xarr.size)

    observed = true_total + noise

    log.setLevel('INFO')  # <\CheatMode>

    # make a spectrum class instance in Tmb units
    xarr._make_header()

    sp = Spectrum(xarr=xarr, data=observed, unit=u.Unit(bunit), header={})
    sp.header['NPEAKS'] = 2
    sp.header['NOISERMS'] = round(signal_peak / snr, 4)
    for comp, name in zip([truth_narrow, truth_wide], ['1', '2']):
        sp.header['AMP_' + name] = comp[0]
        sp.header['XOFF_' + name] = comp[1]
        sp.header['SIG_' + name] = comp[2]
    return sp
def highres_xarr(xarr, N_res, refX):
    # make sure the 11 and 22 cubes are in GHz
    xarr.convert_to_unit(u.GHz)
    xnparr = np.linspace(xarr.min(), xarr.max(), N_res)
    xarr_hires = SpectroscopicAxis(xarr=xnparr,
                                   refX=refX,
                                   velocity_convention="radio")
    return xarr_hires
Exemple #4
0
def get_singv_tau11(singv_para):
    '''
    Take a GAS DR1 parameter maps and return optical depth of the 1-1 line.
    Parameters
    ----------
    sigv_para : str or ndarray
        The GAS DR1 parameter cube (i.e., maps), either as a file name or as a 3D ndarray cube.
    Returns
    -------
    tau11 : ndarray
        A map of model optical depths for ammonia (1-1)
    '''

    # Note: the efficiency could benifit from multi-core processing

    if type(singv_para) == str:
        parcube = fits.getdata(singv_para)

    else:
        parcube = singv_para

    # Create a dummy spectral-axis in km/s as a place holder to acquire tau
    xarr = np.linspace(0.0, 10.0, 10, endpoint=True)
    xarr = SpectroscopicAxis(xarr * u.km / u.s,
                             velocity_convention='radio',
                             refX=freq_dict['oneone'] * u.Hz).as_unit(u.GHz)

    # set ntot elements with zero values to NaN
    parcube[:, parcube[2] == 0.0] = np.nan

    yy, xx = np.indices(parcube.shape[1:])
    nanvals = np.any(~np.isfinite(parcube), axis=0)
    isvalid = np.any(parcube, axis=0) & ~nanvals
    valid_pixels = zip(xx[isvalid], yy[isvalid])

    tau11 = np.zeros(parcube.shape[1:])

    def model_a_pixel(xy):
        x, y = int(xy[0]), int(xy[1])
        kwargs = {
            'tkin': parcube[0, y, x],
            'tex': parcube[1, y, x],
            'ntot': parcube[2, y, x],
            'width': parcube[3, y, x],
            'xoff_v': parcube[4, y, x],
            'fortho': parcube[5, y, x],
            'return_tau': True,
        }
        tau = ammonia.cold_ammonia(xarr, **kwargs)
        tau11[y, x] = tau['oneone']

    for xy in ProgressBar(list(valid_pixels)):
        model_a_pixel(xy)

    return tau11
def test_convert_to_unit(run_with_assert=False):
    for from_unit, to_unit, _, __ in u.doppler_optical(1 * u.Hz):
        sp = SpectroscopicAxis(
            np.linspace(-100, 100, 100), unit=from_unit, refX=23.2 * u.Hz, velocity_convention="optical"
        )
        sp.convert_to_unit(to_unit)
        if run_with_assert:
            assert sp.unit == to_unit
    for from_unit, to_unit, _, __ in u.doppler_radio(1 * u.eV):
        sp = SpectroscopicAxis(
            np.linspace(-100, 100, 100), unit=from_unit, refX=23.2 * u.Hz, velocity_convention="optical"
        )
        sp.convert_to_unit(to_unit)
        if run_with_assert:
            assert sp.unit == to_unit
    for from_unit, to_unit, _, __ in u.doppler_relativistic(1 * u.Angstrom):
        sp = SpectroscopicAxis(
            np.linspace(-100, 100, 100), unit=from_unit, refX=23.2 * u.Hz, velocity_convention="relativistic"
        )
        sp.convert_to_unit(to_unit)
        if run_with_assert:
            assert sp.unit == to_unit
def test_moments():
    xvals = np.linspace(-100, 100, 200) * u.km / u.s
    # Some models will fail without a center frequency and a velocity convention
    xarr = SpectroscopicAxis(xvals,
                             velocity_convention='radio',
                             center_frequency=100 * u.GHz)
    # creating the random data
    rawdata = np.random.randn(xarr.size)

    # creating a sample Spectrum from a .fits file
    sp = Spectrum('test.fits')
    for model_name in sp.specfit.Registry.multifitters.keys():
        print('testing:', model_name)
        model = sp.specfit.Registry.multifitters[model_name]
        params = model.moments(xarr, rawdata, vheight=False)
        print('params from moments:', params)
        assert len(params) == model.npars
        # if this call does not raise an Exception then moments() produced
        # the correct number of parameters
        model.n_modelfunc(pars=params)(xarr)
Exemple #7
0
def load_spectrum(j=6, object='w51e2-tot',
                  npix=1,
                  headerfile='../W51-25GHzcont.map.image.fits',
                  fntemplate='spec-{object}-{j}{j2}-pb.txt',):
    # convert 6 -> 'six' for use below
    linename = ammonia_constants.num_to_name[j] * 2

    # the beam size is important for determining the brighntess conversion
    bm = radio_beam.Beam.from_fits_header(headerfile)

    # read in the file (dumped to text)
    xx,yy=np.loadtxt(fntemplate.format(object=object, j=j, j2=j if j < 10 else ""),
                     comments="#").T
    # we want MEAN flux, not SUM
    yy = yy / npix

    # x units are in km/s, reference is in Hz
    xarr = SpectroscopicAxis(xx*u.km/u.s,
                             refX=ammonia.freq_dict[linename]*u.Hz,
                             velocity_convention='radio')
    sp = pyspeckit.Spectrum(xarr=xarr, data=yy)
    sp.unit = 'Jy'
    # compute the typical noise over the -10 to 10 km/s region
    mean_error = sp.stats((-10,10))['std']
    sp.error[:] = mean_error
    sp.specname = '{0} {1}'.format(object, linename)

    # Copy the spectrum so we can convert it to Kelvins
    spK = sp.copy()
    jytok = ((1*u.Jy).to(u.K, u.brightness_temperature(bm, sp.xarr.refX)).value)
    sp.header['JYTOK'] = jytok
    spK.unit = 'K'
    spK.data = sp.data * jytok
    spK.error = sp.error * jytok
    mean_error_k = mean_error * jytok

    return sp, spK, mean_error, mean_error_k
Exemple #8
0
import numpy as np
import pyspeckit
from astropy import units as u
from pyspeckit.spectrum.models import ammonia_constants, ammonia, ammonia_hf
from pyspeckit.spectrum.models.ammonia_constants import freq_dict
from pyspeckit.spectrum.units import SpectroscopicAxis, SpectroscopicAxes

# Step 1. Generate a synthetic spectrum.  Already have a real spectrum?  Skip
# to step 2!
# Generate a synthetic spectrum based off of 3 NH3 lines
# 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
def hmm1_cubefit(vmin=3.4,
                 vmax=5.0,
                 tk_ave=10.,
                 do_plot=False,
                 snr_min=5.0,
                 multicore=1,
                 do_thin=False):
    """
    Fit NH3(1,1) and (2,2) cubes for H-MM1.
    It fits all pixels with SNR larger than requested. 
    Initial guess is based on moment maps and neighboring pixels. 
    The fitting can be done in parallel mode using several cores, 
    however, this is dangerous for large regions, where using a 
    good initial guess is important. 
    It stores the result in a FITS cube. 

    TODO:
    -convert FITS cube into several FITS files
    -Improve initial guess
    
    Parameters
    ----------
    vmin : numpy.float
        Minimum centroid velocity to plot, in km/s.
    vmax : numpy.float
        Maximum centroid velocity to plot, in km/s.
    tk_ave : numpy.float
        Mean kinetic temperature of the region, in K.
    do_plot : bool
        If True, then a map of the region to map is shown.
    snr_min : numpy.float
        Minimum signal to noise ratio of the spectrum to be fitted.
    multicore : int
        Numbers of cores to use for parallel processing. 
    """

    cube11sc = SpectralCube.read(OneOneFile)
    cube22sc = SpectralCube.read(TwoTwoFile)
    cube11_v = cube11sc.with_spectral_unit(u.km / u.s,
                                           velocity_convention='radio',
                                           rest_value=freq11)
    cube22_v = cube22sc.with_spectral_unit(u.km / u.s,
                                           velocity_convention='radio',
                                           rest_value=freq22)
    from pyspeckit.spectrum.units import SpectroscopicAxis
    spec11 = SpectroscopicAxis(cube11_v.spectral_axis,
                               refX=freq11,
                               velocity_convention='radio')
    spec22 = SpectroscopicAxis(cube22_v.spectral_axis,
                               refX=freq22,
                               velocity_convention='radio')

    errmap11 = fits.getdata(RMSFile_11)
    errmap22 = fits.getdata(RMSFile_22)
    errmap_K = errmap11  #[errmap11, errmap22]
    Tpeak11 = fits.getdata(OneOnePeak)

    moment1 = fits.getdata(OneOneMom1)
    moment2 = (fits.getdata(OneOneMom2))**0.5

    snr = cube11sc.filled_data[:].value / errmap11
    peaksnr = Tpeak11 / errmap11

    planemask = (peaksnr > snr_min)  # *(errmap11 < 0.15)
    planemask = remove_small_objects(planemask, min_size=40)
    planemask = opening(planemask, disk(1))
    #planemask = (peaksnr>20) * (errmap11 < 0.2)

    mask = (snr > 3) * planemask

    maskcube = cube11sc.with_mask(mask.astype(bool))
    maskcube = maskcube.with_spectral_unit(u.km / u.s,
                                           velocity_convention='radio')
    slab = maskcube.spectral_slab(vmax * u.km / u.s, vmin * u.km / u.s)
    w11 = slab.moment(order=0, axis=0).value
    peakloc = np.nanargmax(w11)
    ymax, xmax = np.unravel_index(peakloc, w11.shape)

    moment2[np.isnan(moment2)] = 0.2
    moment2[moment2 < 0.2] = 0.2

    ## Load FITS files
    cube11 = pyspeckit.Cube(OneOneFile, maskmap=planemask)
    cube22 = pyspeckit.Cube(TwoTwoFile, maskmap=planemask)
    # Stack files
    cubes = pyspeckit.CubeStack([cube11, cube22], maskmap=planemask)
    cubes.unit = "K"
    # Define initial guess
    guesses = np.zeros((6, ) + cubes.cube.shape[1:])
    moment1[moment1 < vmin] = vmin + 0.2
    moment1[moment1 > vmax] = vmax - 0.2
    guesses[0, :, :] = tk_ave  # Kinetic temperature
    guesses[1, :, :] = 7  # Excitation  Temp
    guesses[2, :, :] = 14.5  # log(column)
    guesses[
        3, :, :] = moment2  # Line width / 5 (the NH3 moment overestimates linewidth)
    guesses[4, :, :] = moment1  # Line centroid
    guesses[5, :, :] = 0.5  # F(ortho) - ortho NH3 fraction (fixed)
    if do_plot:
        import matplotlib.pyplot as plt
        plt.imshow(w11 * planemask, origin='lower')
        plt.show()
    print('start fit')
    cubes.specfit.Registry.add_fitter('cold_ammonia',
                                      ammonia.cold_ammonia_model(), 6)
    if do_thin:
        file_out = "{0}H-MM1_cold_parameter_maps_snr{1}_thin_v1.fits".format(
            fit_dir, snr_min)
    else:
        file_out = "{0}H-MM1_cold_parameter_maps_snr{1}_thick_v1.fits".format(
            fit_dir, snr_min)
    cubes.fiteach(fittype='cold_ammonia',
                  guesses=guesses,
                  integral=False,
                  verbose_level=3,
                  fixed=[do_thin, False, False, False, False, True],
                  signal_cut=2,
                  limitedmax=[True, False, False, False, True, True],
                  maxpars=[20, 15, 20, 0.4, vmax, 1],
                  limitedmin=[True, True, True, True, True, True],
                  minpars=[5, 2.8, 12.0, 0.05, vmin, 0],
                  start_from_point=(xmax, ymax),
                  use_neighbor_as_guess=True,
                  position_order=1 / peaksnr,
                  errmap=errmap_K,
                  multicore=multicore)
    # Store fits into FITS cube
    fitcubefile = fits.PrimaryHDU(data=np.concatenate(
        [cubes.parcube, cubes.errcube]),
                                  header=cubes.header)
    fitcubefile.header.set('PLANE1', 'TKIN')
    fitcubefile.header.set('PLANE2', 'TEX')
    fitcubefile.header.set('PLANE3', 'COLUMN')
    fitcubefile.header.set('PLANE4', 'SIGMA')
    fitcubefile.header.set('PLANE5', 'VELOCITY')
    fitcubefile.header.set('PLANE6', 'FORTHO')
    fitcubefile.header.set('PLANE7', 'eTKIN')
    fitcubefile.header.set('PLANE8', 'eTEX')
    fitcubefile.header.set('PLANE9', 'eCOLUMN')
    fitcubefile.header.set('PLANE10', 'eSIGMA')
    fitcubefile.header.set('PLANE11', 'eVELOCITY')
    fitcubefile.header.set('PLANE12', 'eFORTHO')
    fitcubefile.header.set('CDELT3', 1)
    fitcubefile.header.set('CTYPE3', 'FITPAR')
    fitcubefile.header.set('CRVAL3', 0)
    fitcubefile.header.set('CRPIX3', 1)
    fitcubefile.writeto(file_out, overwrite=True)
def test_convert_to_unit(run_with_assert=False):
    for from_unit, to_unit, _, __ in u.doppler_optical(1 * u.Hz):
        sp = SpectroscopicAxis(np.linspace(-100, 100, 100),
                               unit=from_unit,
                               refX=23.2 * u.Hz,
                               velocity_convention='optical')
        sp.convert_to_unit(to_unit)
        if (run_with_assert):
            assert sp.unit == to_unit
    for from_unit, to_unit, _, __ in u.doppler_radio(1 * u.eV):
        sp = SpectroscopicAxis(np.linspace(-100, 100, 100),
                               unit=from_unit,
                               refX=23.2 * u.Hz,
                               velocity_convention='optical')
        sp.convert_to_unit(to_unit)
        if (run_with_assert):
            assert sp.unit == to_unit
    for from_unit, to_unit, _, __ in u.doppler_relativistic(1 * u.Angstrom):
        sp = SpectroscopicAxis(np.linspace(-100, 100, 100),
                               unit=from_unit,
                               refX=23.2 * u.Hz,
                               velocity_convention='relativistic')
        sp.convert_to_unit(to_unit)
        if (run_with_assert):
            assert sp.unit == to_unit
Exemple #11
0
def get_SNR(paraname, savename=None, rms=0.15, n_comp=2, linename='oneone'):
    '''
    Take a multiple velocity componet fit and produce a signal to noise ratio of the two velocity components
    :param paraname:
    :param savename:
    :param rms:
    :param n_comp:
    :return:
    '''

    para, hdr = fits.getdata(paraname, header=True)
    n_para = n_comp * 4

    # remove the error components
    para = para[:n_para]
    assert para.shape[0] == n_para

    yy, xx = np.indices(para.shape[1:])
    nanvals = np.any(~np.isfinite(para), axis=0)
    isvalid = np.any(para, axis=0) & ~nanvals
    valid_pixels = zip(xx[isvalid], yy[isvalid])

    # Create a synthetic X-dimension in km/s
    vres = 0.07
    vpad = 0.5
    vmax, vmin = np.argmax([para[0], para[4]]), np.argmin([para[0], para[4]])
    vmax = vmax + vpad
    vmin = vmin - vpad
    n_samp = (vmax - vmin) / vres

    xarr = np.linspace(vmin, vmax, int(n_samp) + 1, endpoint=True)
    xarr = SpectroscopicAxis(xarr * u.km / u.s,
                             velocity_convention='radio',
                             refX=freq_dict[linename] * u.Hz).as_unit(u.GHz)

    peakT = np.zeros((n_comp, para.shape[1], para.shape[2]))

    def model_a_pixel(xy):
        x, y = int(xy[0]), int(xy[1])
        models = [
            ammonia._ammonia_spectrum(xarr.as_unit('GHz'),
                                      tex=tex,
                                      tau_dict={linename: tau},
                                      width=width,
                                      xoff_v=vel,
                                      fortho=0.0,
                                      line_names=[linename])
            for vel, width, tex, tau in zip(para[::4, y, x], para[1::4, y, x],
                                            para[2::4, y, x], para[3::4, y, x])
        ]
        peakT[:, y, x] = np.nanmax(models, axis=1)

    for xy in ProgressBar(list(valid_pixels)):
        print int(xy[0]), int(xy[1])
        model_a_pixel(xy)

    if savename != None:

        for i in np.arange(n_comp * 8) + 1:
            key = 'PLANE{0}'.format(i)
            if key in hdr:
                hdr.remove(key)

        newfits = fits.PrimaryHDU(data=peakT / rms, header=hdr)
        newfits.header.set('CDELT3', 1)
        newfits.header.set('CTYPE3', 'FITPAR')
        newfits.header.set('PLANE1', 'SNR_0')
        newfits.header.set('PLANE2', 'SNR_1')
        newfits.header.set('NAXIS3', n_comp * 8)
        newfits.writeto(savename, overwrite=True)

    return peakT / rms
Exemple #12
0
from astropy.table import Table
import numpy as np
import matplotlib.pyplot as plt
import scipy.interpolate as interp
import astropy.units as u
from pyspeckit.spectrum.units import SpectroscopicAxis 
from pyspeckit.spectrum.models.h2co_mm import h2co_mm_radex

import mmh2co_model as model

t = Table.read('ph2cogrid.fits.gz',format='fits')

bundle = model.H2COModel(t)

nu = SpectroscopicAxis(np.linspace(218e9,219e9,1000)*u.Hz)
spec = h2co_mm_radex(nu,gridbundle=bundle,verbose=True,Temperature=15,width=1.0)
plt.plot(nu.as_unit('GHz'),spec)
plt.show()
def spec_curve_fit(bin_num, map_name=map_column_dens):
    # following loop has not good style. One should build in some break statements or error messages
    # if files repeatedly appear in loop.
    for one_file in files:
        if 'NH3_11' in one_file:
            file_name_NH3_11 = one_file
        if 'NH3_22' in one_file:
            file_name_NH3_22 = one_file
        if 'NH3_33' in one_file:
            file_name_NH3_33 = one_file

    y, x, med = binning(bin_width, bin_num)

    s11, _, offset_velocity11, sp_av11 = averaging_over_dopplervel(
        file_name_NH3_11, y, x)
    s22, _, offset_velocity22, sp_av22 = averaging_over_dopplervel(
        file_name_NH3_22, y, x)
    s33, _, offset_velocity33, sp_av33 = averaging_over_dopplervel(
        file_name_NH3_33, y, x)

    xarr11 = SpectroscopicAxis(offset_velocity11 * u.km / u.s,
                               velocity_convention='radio',
                               refX=freq_dict['oneone']).as_unit(u.GHz)
    xarr22 = SpectroscopicAxis(offset_velocity22 * u.km / u.s,
                               velocity_convention='radio',
                               refX=freq_dict['twotwo']).as_unit(u.GHz)
    xarr33 = SpectroscopicAxis(offset_velocity33 * u.km / u.s,
                               velocity_convention='radio',
                               refX=freq_dict['threethree']).as_unit(u.GHz)

    sp11 = psk.Spectrum(data=s11,
                        xarr=xarr11,
                        xarrkwargs={'unit': 'km/s'},
                        unit='K')
    sp22 = psk.Spectrum(data=s22,
                        xarr=xarr22,
                        xarrkwargs={'unit': 'km/s'},
                        unit='K')
    sp33 = psk.Spectrum(data=s33,
                        xarr=xarr33,
                        xarrkwargs={'unit': 'km/s'},
                        unit='K')

    # This joins all the spectra together into one object.
    allspec = psk.Spectra([sp11, sp22, sp33])
    allspec.xarr.as_unit('Hz', velocity_convention='radio')
    # This add the cold_ammonia model to the list of things we can use for fitting
    allspec.specfit.Registry.add_fitter('cold_ammonia',
                                        ammonia.cold_ammonia_model(), 6)
    # This does the fit.  The values of the guess are
    # Kinetic Temperature (usually about 15 to 25 K)
    # Excitation Temperature (between 2.73 K and the excitation temperature)
    # Log Column Density of ammonia
    # Line width (~1 km/s)
    # Offset velocity (you will usually use 0 instead of 8.5)
    # Ortho fraction (leave at 0)
    allspec.specfit(fittype='cold_ammonia', guesses=[23, 5, 13.1, 1, 0, 0])

    # You can make a plot here.
    fig = plt.figure()
    allspec.plotter()
    allspec.specfit.plot_fit(lw=1, components=True)
    plt.xlim((23.692, 23.697))
    #     plt.xlim((23.72,23.725))
    #     plt.xlim((23.8692, 23.8708))
    #     plt.savefig("OrionA:pyspeckit_fit_bin_width=%rthis_bin=%r.ps" %(bin_width, this_bin))
    plt.savefig("Map=%r:bin_num=%r_pyspeckit_fit_NH3_11TEST.ps" %
                (map_name, bin_num))
    plt.show()

    # returns the values of the fitted parameters: T_K, T_ex, N, sigma, v, F_0
    return allspec.specfit.parinfo, allspec.specfit.parinfo.errors
Exemple #14
0
import pkgutil
import os
import importlib
from pyspeckit.spectrum.models.inherited_gaussfitter import gaussian_fitter
from pyspeckit.spectrum.units import SpectroscopicAxis
import numpy as np
import pyspeckit.spectrum.models as models

models_path = os.path.dirname(models.__file__)
xarr = np.linspace(-100, 100, 200)
names = [name for _, name, _ in pkgutil.iter_modules([models_path])]
for name in names:
    try:
        model_name = 'pyspeckit.spectrum.models.' + name
        model_module = importlib.import_module(model_name)
        model = getattr(model_module, name + '_model')
        model_instance = model()
        moments = getattr(model, 'moments')
        rawdata = np.random.randn(xarr.size)
        params = model_instance.moments(xarr, rawdata)
        print 'params:', params
        xarr = SpectroscopicAxis(xarr)
        # if moments() returns wrong number of parameters this should fail
        print model_instance.n_modelfunc(pars=params)(xarr)
    except Exception as e:
        print e
Exemple #15
0
                      mg=1,
                      isg1=1,
                      isg2=1)
 for j in np.arange(nts):
     T11 = T11_thy + np.random.randn(len(v_axis)) * rms
     T22 = T22_thy + np.random.randn(len(v_axis)) * rms
     # ------------ hf Trot ---------------
     S11_mg = np.sum(T11[i11_m] * cw)
     S11_isg = np.sum(T11[i11_isg0]) * cw + np.sum(T11[i11_isg1]) * cw
     S11_osg = np.sum(T11[i11_osg0]) * cw + np.sum(T11[i11_osg1]) * cw
     S22_mg = np.sum(T22[i22_mg] * cw)
     S22_isg = np.sum(T22[i22_isg0]) * cw + np.sum(T22[i22_isg1]) * cw
     Tex_hf = Tex_main(S11_mg, S11_isg, S11_osg, S22_mg, S22_isg, dv=dv)
     # ----------- speckit Tex ------------
     xarr11 = SpectroscopicAxis(v_axis * u.km / u.s,
                                velocity_convention='radio',
                                refX=freq_dict['oneone']).as_unit(u.GHz)
     xarr22 = SpectroscopicAxis(v_axis * u.km / u.s,
                                velocity_convention='radio',
                                refX=freq_dict['twotwo']).as_unit(u.GHz)
     xarr = SpectroscopicAxes([xarr11, xarr22])
     synthspec = np.hstack((T11, T22))
     nh3_sp = pyspeckit.Spectrum(xarr=xarr, data=synthspec, header={})
     # nh3_sp.plotter(axis=nh3_sp.plotter.axis,clear=True)
     # trot=20, tex=None, ntot=14.8, width=1, xoff_v=0.0, fortho=0.5
     # nh3_sp.plotter(axis=ax1, clear=False)  # axis=ax1
     nh3_sp.specfit(
         fittype='ammonia_tau',
         guesses=[Tex_ini, Tex_ini - 10, tau_1 / 2, dv / d2s, 0, 0.5],
         fixed=[0, 1, 0, 1, 1, 1])
     Tex_kit = nh3_sp.specfit.parinfo[0]['value']
from __future__ import print_function
import numpy as np
from pyspeckit import SpectralCube
from pyspeckit.spectrum.units import SpectroscopicAxis
from pyspeckit.spectrum.models.inherited_gaussfitter import gaussian_fitter
from astropy import units as u
import matplotlib.pyplot as plt
import pytest
from astropy import log

xarr = SpectroscopicAxis(np.linspace(-100, 100, 50),
                         unit=u.dimensionless_unscaled)
gf = gaussian_fitter()
params = [1.0, 2.0, 5.0]
parameter_error_amplitude = [50., 5., 5.]
assertion_list = []
passes = {'passes': [0, 0, 0], 'avg_difference': [0, 0, 0]}
fails = {'fails': [0, 0, 0], 'avg_difference': [0, 0, 0]}


@pytest.mark.parametrize(("rawdata", "noise"), [(gf.n_modelfunc(pars=params)(
    xarr.value), np.random.randn(xarr.value.size) / 100.)])
def test_fiteach(rawdata, noise):
    for i in range(1):
        passed = True
        parameter_noise = [
            params[0] + abs(np.random.randn()) * parameter_error_amplitude[0],
            params[1] + abs(np.random.randn()) * parameter_error_amplitude[1],
            params[2] + abs(np.random.randn()) * parameter_error_amplitude[2]
        ]
        guesses = np.array(params) + parameter_noise
Exemple #17
0
T0 = (const.h * rest_freq / const.k_B).decompose().value


def J_nu(T, T_nu):
    ''' Brightness temperature calculated in the R-J regime
    '''
    return T_nu / (np.exp(T_nu / T) - 1)


#
#
rms_thin = 0.001
rms_thick = 0.3
#
xarr = SpectroscopicAxis(
    np.linspace(93164661398.45563, 93182630148.45563, num=921) * u.Hz,
    refX=rest_freq)
# thin
signal_thin = pyspeckit.models.n2hp.n2hp_vtau.hyperfine(xarr,
                                                        Tex=9.0,
                                                        tau=0.01,
                                                        xoff_v=0.0,
                                                        width=0.3)
signal_thin += rms_thin * np.random.randn(len(signal_thin))
signal_thin = np.float32(signal_thin)
# thick
signal_thick = pyspeckit.models.n2hp.n2hp_vtau.hyperfine(xarr,
                                                         Tex=9.0,
                                                         tau=9.0,
                                                         xoff_v=0.0,
                                                         width=0.3)
Exemple #18
0
try:
    import scipy
    scipyOK = True
except ImportError:
    scipyOK = False

if scipyOK:
    import numpy as np
    import pyspeckit.spectrum.models.inherited_voigtfitter as IV
    from pyspeckit.spectrum.units import SpectroscopicAxis

    xarr = SpectroscopicAxis(np.linspace(-100, 100, 1000))
    dx = np.diff(xarr).mean()

    V1 = IV.voigt(xarr, 1, 0, 1, 1, normalized=False)
    V2 = IV.voigt(xarr, 1, 0, 1, 1, normalized=True)

    assert np.sqrt(2 * np.pi) - 0.05 < V1.sum() * dx.value < np.sqrt(
        2 * np.pi) + 0.05
    assert 0.99 < V2.sum() * dx.value < 1.01
else:
    print("Skipped Voigt test because scipy could not be imported")