def basefit(hdu, mode='auto', *args, **kwargs):
    import time
    import numpy
    import pyfits
    import analyse

    print('basefit: mode=%s'%(mode))

    if mode.lower()=='simple':
        fitfunc = basefit_simple
    elif mode.lower()=='auto':
        fitfunc = basefit_auto

    v = analyse.generate_axis(hdu, axis=3)
    fitted, emission_flag = fitfunc(hdu, v, *args, **kwargs)

    header = hdu.header.copy()
    header.add_history('pyanalyse.basefit: generate fitted data (mode:%s)'%mode)
    header.add_history('pyanalyse.basefit: time stamp (%s)'%time.strftime('%Y/%m/%d %H:%M:%S'))

    ef_header = hdu.header.copy()
    ef_header.add_history('pyanalyse.basefit: generate emission flag (mode:%s)'%mode)
    ef_header.add_history('pyanalyse.basefit: time stamp (%s)'%time.strftime('%Y/%m/%d %H:%M:%S'))

    fitted_data = pyfits.PrimaryHDU(fitted, header)
    flag = pyfits.PrimaryHDU(emission_flag, ef_header)

    return fitted_data, flag
def draw_otf_spectrum(cube, figure=None, subplot=111, title='', grid=True,
                      font_family=None, tick_labels_size=9, xlim=None, ylim=None,
                      show=True, *args, **kwargs):
    import time
    import numpy
    import analyse
    import analyse.plotter
    import matplotlib.figure
    import matplotlib.colors
    import pylab
    t0 = time.time()
    print('[%f] -- %f'%(time.time(), time.time()-t0))
    if not isinstance(figure, matplotlib.figure.Figure):
        if figure is None:
            figure = pylab.figure()
        else:
            figure = pylab.figure(figsize=figure)
    else:
        show = False

    if type(subplot) is int:
        subplot = analyse.plotter.get_subplot(subplot)
    elif type(subplot) in [list, tuple]:
        if len(subplot) == 3:
            subplot = analyse.plotter.get_subplot(subplot)

    nz, ny, nx = cube.data.shape
    spectra = cube.data.T.reshape(nx*ny, nz)
    v = analyse.generate_axis(cube, axis=3) / 1000.

    ax = figure.add_axes(subplot)
    #[ax.plot(v, s, '.b', ms=1, mew=0, alpha=0.1) for s in spectra]
    xd = numpy.array(list(v) * len(spectra))
    yd = spectra.ravel()
    yd[numpy.isnan(yd)] = 0
    histmap, histx, histy = pylab.histogram2d(xd, yd, bins=501)
    histmap = histmap.T
    histmap[numpy.where(histmap==0)] = 0.3
    histmap = numpy.log10(histmap)
    histX, histY = numpy.meshgrid(histx, histy)
    ax.pcolormesh(histX, histY, histmap, vmax=3.3)
    ax.grid(grid)
    ax.set_title(title, size=tick_labels_size+1)
    if xlim is not None: ax.set_xlim(*xlim)
    else: ax.set_xlim(xd.min(), xd.max())
    if ylim is not None: ax.set_ylim(*ylim)
    else: ax.set_ylim(yd.min(), yd.max())
    tx = ax.get_xticks()
    ty = ax.get_yticks()
    ax.set_xticklabels(tx, size=tick_labels_size)
    ax.set_yticklabels(ty, size=tick_labels_size)

    if show:
        pylab.show()

    print('[%f] -- %f'%(time.time(), time.time()-t0))
    return figure
def draw_ps_spectrum(cube, figure=None, subplot=111, title='', grid=True,
                      font_family=None, tick_labels_size=9, show=True, *args, **kwargs):
    import analyse
    import analyse.plotter
    import pylab
    import matplotlib

    def_font_size = matplotlib.rcParams['font.size']
    def_font_family = matplotlib.rcParams['font.family']
    matplotlib.rcParams['font.size'] = tick_labels_size
    if font_family is not None: matplotlib.rcParams['font.family'] = font_family

    if figure is None:
        figure = pylab.figure()
    else:
        show = False

    if type(subplot) is int:
        subplot = analyse.plotter.get_subplot(subplot)
    elif type(subplot) in [list, tuple]:
        if len(subplot) == 3:
            subplot = analyse.plotter.get_subplot(subplot)

    nz, ny, nx = cube.data.shape
    spectra = cube.data.T.reshape(nx*ny, nz)
    v = analyse.generate_axis(cube, axis=3) / 1000.

    ax = figure.add_axes(subplot)
    [ax.plot(v, s) for s in spectra]
    ax.grid(grid)
    ax.set_title(title)

    if show:
        pylab.show()

    matplotlib.rcParams['font.size'] = def_font_size
    matplotlib.rcParams['font.family'] = def_font_family
    return figure
def draw_ss_spectrum(cube, flag, figure=None, subplot=111, title='', grid=True,
                      font_family=None, tick_labels_size=9, show=True, *args, **kwargs):
    import analyse
    import analyse.plotter
    import pylab
    import numpy
    import matplotlib

    tpeak, rms = analyse_ss(cube, flag)

    def_font_size = matplotlib.rcParams['font.size']
    def_font_family = matplotlib.rcParams['font.family']
    matplotlib.rcParams['font.size'] = tick_labels_size
    if font_family is not None: matplotlib.rcParams['font.family'] = font_family

    if figure is None:
        figure = pylab.figure()
    else:
        show = False

    if type(subplot) is int:
        subplot = analyse.plotter.get_subplot(subplot)
    elif type(subplot) in [list, tuple]:
        if len(subplot) == 3:
            subplot = analyse.plotter.get_subplot(subplot)

    nz, ny, nx = cube.data.shape
    spectra = cube.data.T.reshape(nx*ny, nz)
    v = analyse.generate_axis(cube, axis=3) / 1000.

    ax = figure.add_axes(subplot)
    [ax.plot(v, s) for s in spectra]
    ax.grid(grid)
    ax.set_title(title)
    """
    if fits_params['MOLECULE']=='12CO': tmb = float(sslist['tmb12'])
    elif fits_params['MOLECULE']=='13CO': tmb = float(sslist['tmb13'])
    elif fits_params['MOLECULE']=='C18O': tmb = float(sslist['tmb18'])
    else: pass
    """
    # 判断の参考に参考にTmbが○%のところに線を引く
    """
    xs = float(sslist['v_center']) - float(sslist['v_width'])/2.
    xe = float(sslist['v_center']) + float(sslist['v_width'])/2.
    """
    ###### atodekesu #####
    xs = -41.       #
    xe = 55.        #
    tmb = 40.       #
    ###### atodekesu #####
    percents = numpy.arange(50, 101, 10)
    percent_lines = tmb * percents / 100.
    [pylab.axhline(y=_y, color='r', linestyle='--', linewidth=2, alpha=0.5) for _y in percent_lines]
    [ax.text(xs, _y, str(_p)+'%') for _y, _p in zip(percent_lines, percents)]
    ax.set_ylim(-2, tmb*1.2)
    ax.set_ylabel('Ta* [K]')
    ax.set_xlabel('km/s')
    ax.set_xlim(xs, xe)
    #ax.set_title('%s %s' % (fits_params['OBJECT'], fits_params['DATE-OBS']))
    ax.annotate('Tpeak=%.2f [K]\nTmb=%.2f [K]\neff.=%.2f\nTrms=%.2f [K]'%(tpeak, tmb, tpeak/tmb, rms), xy=(.65,.85), xycoords='axes fraction')

    """
    if str(fits_params['BACKEND'])[-1]==1: direction='H'
    elif str(fits_params['BACKEND'])[-1]==2: direction='V'
    else: pass
    """

    if show:
        pylab.show()

    matplotlib.rcParams['font.size'] = def_font_size
    matplotlib.rcParams['font.family'] = def_font_family
    return figure