Ejemplo n.º 1
0
    def main(args):
        t = time.perf_counter()

        if args.bgagg:
            pyplot.switch_backend('agg')

        redux_path = manga.drp_redux_path(drpver=args.drpver) \
                            if args.redux_path is None else Path(args.redux_path).resolve()
        analysis_path = manga.dap_analysis_path(drpver=args.drpver, dapver=args.dapver) \
                            if args.analysis_path is None else Path(args.analysis_path).resolve()

        plan = manga.MaNGAAnalysisPlan.default(analysis_path=analysis_path) \
                    if args.plan_file is None \
                    else manga.MaNGAAnalysisPlan.from_toml(args.plan_file,
                                                           analysis_path=analysis_path)

        drpall_file = manga.drpall_file(drpver=args.drpver,
                                        redux_path=redux_path)
        dapall_file = manga.dapall_file(drpver=args.drpver,
                                        dapver=args.dapver,
                                        analysis_path=analysis_path)

        drpall_hdu = fits.open(str(drpall_file))
        dapall_hdu = fits.open(str(dapall_file))

        eml = channel_dictionary(dapall_hdu, 0, prefix='ELG')
        spi = channel_dictionary(dapall_hdu, 0, prefix='SPI')

        for i, key in enumerate(plan.keys()):
            dapall_qa(drpall_hdu['MANGA'].data,
                      dapall_hdu[plan[key]['key']].data, analysis_path,
                      plan[key]['key'], eml, spi)

        print('Elapsed time: {0} seconds'.format(time.perf_counter() - t))
Ejemplo n.º 2
0
def get_emission_line_fom_maps(dapmaps):

    maps_hdu = fits.open(dapmaps)
    eml = channel_dictionary(maps_hdu, 'EMLINE_GFLUX')
    anr = numpy.ma.MaskedArray(
        maps_hdu['EMLINE_GANR'].data[eml['Ha-6564'], ...],
        mask=maps_hdu['EMLINE_GFLUX_MASK'].data[eml['Ha-6564'], ...] > 0)
    ha = numpy.ma.MaskedArray(
        maps_hdu['EMLINE_GFLUX'].data[eml['Ha-6564'], ...],
        mask=maps_hdu['EMLINE_GFLUX_MASK'].data[eml['Ha-6564'], ...] > 0)
    hb = numpy.ma.MaskedArray(
        maps_hdu['EMLINE_GFLUX'].data[eml['Hb-4862'], ...],
        mask=maps_hdu['EMLINE_GFLUX_MASK'].data[eml['Hb-4862'], ...] > 0)
    aob = numpy.ma.divide(ha, hb)

    # Get the associated S/N and fit metrics
    rms = numpy.ma.MaskedArray(maps_hdu['EMLINE_FOM'].data[0, :, :])
    rms[numpy.invert(rms > 0)] = numpy.ma.masked
    frms = numpy.ma.MaskedArray(maps_hdu['EMLINE_FOM'].data[1, :, :])
    frms[numpy.invert(frms > 0)] = numpy.ma.masked
    rchi2 = numpy.ma.MaskedArray(maps_hdu['EMLINE_FOM'].data[2, :, :])
    rchi2[numpy.invert(rchi2 > 0)] = numpy.ma.masked
    chi_grw = numpy.ma.MaskedArray(maps_hdu['EMLINE_FOM'].data[6:, :, :])
    chi_grw[numpy.invert(chi_grw > 0)] = numpy.ma.masked

    extent = map_extent(maps_hdu, 'SPX_MFLUX')

    return extent, anr, aob, rms, frms, rchi2, chi_grw
Ejemplo n.º 3
0
def compile_data(dapver, analysis_path, daptype, plt):

    ifus = [
        1901, 1902, 3701, 3702, 3703, 3704, 6101, 6102, 6103, 6104, 9101, 9102,
        12701, 12702, 12703, 12704, 12705
    ]

    sc_pltifu = []
    sc_snrg = []
    sc_frms = []
    sc_rchi = []

    el_pltifu = []
    el_snrg = []
    el_frms = []
    el_rchi = []

    for ifu in ifus:
        apath = os.path.join(analysis_path, daptype, str(plt), str(ifu))
        maps_file = os.path.join(
            apath, 'manga-{0}-{1}-MAPS-{2}.fits.gz'.format(plt, ifu, daptype))

        if not os.path.isfile(maps_file):
            continue

        hdu = fits.open(maps_file)

        # Get the stellar data
        uniq, indx = map(
            lambda x: x[1:],
            numpy.unique(hdu['BINID'].data[1, :, :].ravel(),
                         return_index=True))
        mask = hdu['STELLAR_VEL_MASK'].data.ravel()[indx] > 0
        indx = indx[numpy.invert(mask)]

        if len(indx) > 0:
            sc_pltifu += ['{0}-{1}'.format(plt, ifu)]
            sc_snrg += [hdu['BIN_SNR'].data.ravel()[indx]]
            sc_frms += [hdu['STELLAR_FOM'].data[1, :, :].ravel()[indx]]
            sc_rchi += [hdu['STELLAR_FOM'].data[2, :, :].ravel()[indx]]

        # Get the emission-line data
        eml = channel_dictionary(hdu, 'EMLINE_GFLUX')
        uniq, indx = map(
            lambda x: x[1:],
            numpy.unique(hdu['BINID'].data[3, :, :].ravel(),
                         return_index=True))
        mask = hdu['EMLINE_GFLUX_MASK'].data[
            eml['Ha-6564'], :, :].ravel()[indx] > 0
        indx = indx[numpy.invert(mask)]

        if len(indx) > 0:
            el_pltifu += ['{0}-{1}'.format(plt, ifu)]
            el_snrg += [hdu['SPX_SNR'].data.ravel()[indx]]
            el_frms += [hdu['EMLINE_FOM'].data[1, :, :].ravel()[indx]]
            el_rchi += [hdu['EMLINE_FOM'].data[2, :, :].ravel()[indx]]

    return ifus, numpy.array(sc_pltifu), sc_snrg, sc_frms, sc_rchi, numpy.array(el_pltifu), \
                el_snrg, el_frms, el_rchi
Ejemplo n.º 4
0
def main(args):
    t = time.perf_counter()

    if args.bgagg:
        pyplot.switch_backend('agg')

    # Set the paths
    redux_path = defaults.drp_redux_path(drpver=args.drpver) \
                        if args.redux_path is None else args.redux_path
    analysis_path = defaults.dap_analysis_path(drpver=args.drpver, dapver=args.dapver) \
                            if args.analysis_path is None else args.analysis_path

    daptypes = []
    if args.daptype is None:
        analysisplan = AnalysisPlanSet.default() if args.plan_file is None \
                            else AnalysisPlanSet.from_par_file(args.plan_file)
        for p in analysisplan:
            bin_method = SpatiallyBinnedSpectra.define_method(p['bin_key'])
            sc_method = StellarContinuumModel.define_method(p['continuum_key'])
            el_method = EmissionLineModel.define_method(p['elfit_key'])
            daptypes += [
                defaults.dap_method(
                    bin_method['key'],
                    sc_method['fitpar']['template_library_key'],
                    el_method['continuum_tpl_key'])
            ]
    else:
        daptypes = [args.daptype]

    drpall_file = defaults.drpall_file(drpver=args.drpver,
                                       redux_path=redux_path)
    dapall_file = defaults.dapall_file(drpver=args.drpver,
                                       dapver=args.dapver,
                                       analysis_path=analysis_path)

    drpall_hdu = fits.open(drpall_file)
    dapall_hdu = fits.open(dapall_file)

    eml = channel_dictionary(dapall_hdu, 0, prefix='ELG')
    spi = channel_dictionary(dapall_hdu, 0, prefix='SPI')

    for daptype in daptypes:
        dapall_qa(drpall_hdu['MANGA'].data, dapall_hdu[daptype].data,
                  analysis_path, daptype, eml, spi)

    print('Elapsed time: {0} seconds'.format(time.perf_counter() - t))
Ejemplo n.º 5
0
def ppxf_flag_info(tbl, maps_file):
    qual_bm = DAPQualityBitMask()
    bm = DAPMapsBitMask()
   
#    # Targeting bits
#    sdssMaskbits = defaults.sdss_maskbits_file()
#    mngtarg1_bm = BitMask.from_par_file(sdssMaskbits, 'MANGA_TARGET1')
#    mngtarg3_bm = BitMask.from_par_file(sdssMaskbits, 'MANGA_TARGET3')

    tbl['PLT'], tbl['IFU'] = map(lambda x : int(x), os.path.split(maps_file)[1].split('-')[1:3])

    with fits.open(maps_file) as hdu:

        # Check if the file was CRITICAL
        tbl['CRIT'] = qual_bm.flagged(hdu['PRIMARY'].header['DAPQUAL'], flag='DRPCRIT')
        tbl['MAIN'] = hdu[0].header['MNGTARG1'] > 0

        el = channel_dictionary(hdu, 'EMLINE_GFLUX')

        haflx = numpy.ma.MaskedArray(hdu['EMLINE_GFLUX'].data[el['Ha-6564']],
                                     mask=hdu['EMLINE_GFLUX_MASK'].data[el['Ha-6564']] > 0)
        tbl['HAMEAN'] = numpy.ma.median(haflx)
        tbl['NSPX'] = haflx.size
        tbl['NGOOD'] = numpy.sum(numpy.logical_not(numpy.ma.getmaskarray(haflx)))
        indx = bm.flagged(hdu['EMLINE_GFLUX_MASK'].data[el['Ha-6564']], 'FITFAILED')
        tbl['NFLG'] = numpy.sum(indx)

        if not numpy.any(indx):
            return

        snr = numpy.ma.MaskedArray(hdu['SPX_SNR'].data,
                                   mask=numpy.logical_not(hdu['SPX_SNR'].data > 0))
        tbl['FLGSNR'] = numpy.ma.median(snr[indx])
        srt = numpy.argsort(snr[indx])
        tbl['EXSNR'] = snr[indx][srt][-1]
        tbl['EXBIN'] = hdu['BINID'].data[3][indx][srt][-1]
Ejemplo n.º 6
0
flux = np.ma.MaskedArray(
    hdu_cube['FLUX'].data,
    mask=bm.flagged(hdu_cube['MASK'].data,
                    ['IGNORED', 'FLUXINVALID', 'IVARINVALID', 'ARTIFACT']))
ivar = np.ma.MaskedArray(
    hdu_cube['IVAR'].data,
    mask=bm.flagged(hdu_cube['MASK'].data,
                    ['IGNORED', 'FLUXINVALID', 'IVARINVALID', 'ARTIFACT']))
model = np.ma.MaskedArray(hdu_cube['MODEL'].data,
                          mask=bm.flagged(hdu_cube['MASK'].data, 'FITIGNORED'))

# Read in MAP
hdu_maps = fits.open(fits_maps_fil)
binid = hdu_maps['BINID'].data[1, :, :]
mask_ext = hdu_maps['EMLINE_GVEL'].header['QUALDATA']
emlc = channel_dictionary(hdu_maps, 'EMLINE_GVEL')
emission_vfield = np.ma.MaskedArray(
    hdu_maps['EMLINE_GVEL'].data[emlc['Ha-6564'], :, :],
    mask=hdu_maps[mask_ext].data[emlc['Ha-6564'], :, :] > 0)
emission_vfield_ivar = np.ma.MaskedArray(
    hdu_maps['EMLINE_GVEL_IVAR'].data[emlc['Ha-6564'], :, :],
    mask=hdu_maps[mask_ext].data[emlc['Ha-6564'], :, :] > 0)

mask_ext = hdu_maps['STELLAR_VEL'].header['QUALDATA']
stellar_vfield = np.ma.MaskedArray(hdu_maps['STELLAR_VEL'].data,
                                   mask=hdu_maps[mask_ext].data > 0)
stellar_vfield_ivar = np.ma.MaskedArray(hdu_maps['STELLAR_VEL_IVAR'].data,
                                        mask=hdu_maps[mask_ext].data > 0)

#Plot map of binids, emission line velocities, etc
fig, axes = pl.subplots(1, 3, figsize=(12, 4))
Ejemplo n.º 7
0
def get_halpha_data(plt, ifu, hdu):
    el = channel_dictionary(hdu, 'EMLINE_GFLUX')
    uniq_bins, uniq_indx, uniq_cnt = map(
        lambda x: x[1:],
        numpy.unique(hdu['BINID'].data[3].ravel(),
                     return_index=True,
                     return_counts=True))
    keep = numpy.logical_not(hdu['EMLINE_GFLUX_MASK'].data.ravel()[uniq_indx] > 0) \
            | numpy.logical_not(hdu['EMLINE_GEW_MASK'].data.ravel()[uniq_indx] > 0) \
            | numpy.logical_not(hdu['EMLINE_GVEL_MASK'].data.ravel()[uniq_indx] > 0) \
            | numpy.logical_not(hdu['EMLINE_GSIGMA_MASK'].data.ravel()[uniq_indx] > 0)
    uniq_bins = uniq_bins[keep]
    uniq_indx = uniq_indx[keep]
    uniq_cnt = uniq_cnt[keep]
    data = HalphaDataTable(shape=uniq_bins.shape)

    data['PLATE'] = plt
    data['IFU'] = ifu
    data['Y'], data['X'] = numpy.unravel_index(uniq_indx,
                                               hdu['BINID'].shape[1:])
    data['BINID'] = uniq_bins
    data['R'] = hdu['SPX_ELLCOO'].data[0].ravel()[uniq_indx]
    data['R_RE'] = hdu['SPX_ELLCOO'].data[1].ravel()[uniq_indx]
    data['R_KPC'] = hdu['SPX_ELLCOO'].data[2].ravel()[uniq_indx]
    data['GCNT'] = hdu['SPX_MFLUX'].data.ravel()[uniq_indx]
    data['GSNR'] = hdu['SPX_SNR'].data.ravel()[uniq_indx]
    data['FLUX'] = hdu['EMLINE_GFLUX'].data[el['Ha-6564']].ravel()[uniq_indx]
    data['FLUX_ERR'] = numpy.ma.power(
        hdu['EMLINE_GFLUX_IVAR'].data[el['Ha-6564']].ravel()[uniq_indx],
        -0.5).filled(-1)
    data['AMP'] = hdu['EMLINE_GA'].data[el['Ha-6564']].ravel()[uniq_indx]
    data['ANR'] = hdu['EMLINE_GANR'].data[el['Ha-6564']].ravel()[uniq_indx]
    data['RCHI2'] = hdu['EMLINE_LFOM'].data[el['Ha-6564']].ravel()[uniq_indx]
    data['CNT'] = hdu['EMLINE_GEW_CNT'].data[el['Ha-6564']].ravel()[uniq_indx]
    data['EW'] = hdu['EMLINE_GEW'].data[el['Ha-6564']].ravel()[uniq_indx]
    data['EW_ERR'] = numpy.ma.power(
        hdu['EMLINE_GEW_IVAR'].data[el['Ha-6564']].ravel()[uniq_indx],
        -0.5).filled(-1)
    data['VEL'] = hdu['EMLINE_GVEL'].data[el['Ha-6564']].ravel()[uniq_indx]
    data['VEL_ERR'] = numpy.ma.power(
        hdu['EMLINE_GVEL_IVAR'].data[el['Ha-6564']].ravel()[uniq_indx],
        -0.5).filled(-1)
    data['SIG'] = hdu['EMLINE_GSIGMA'].data[el['Ha-6564']].ravel()[uniq_indx]
    data['SIG_ERR'] = numpy.ma.power(
        hdu['EMLINE_GSIGMA_IVAR'].data[el['Ha-6564']].ravel()[uniq_indx],
        -0.5).filled(-1)
    data['SIG_INST'] = hdu['EMLINE_INSTSIGMA'].data[
        el['Ha-6564']].ravel()[uniq_indx]

    # Deal with the masking
    qual_bm = DAPQualityBitMask()
    data_bm = HalphaBitMask()
    if qual_bm.flagged(hdu[0].header['DAPQUAL'], flag='CRITICAL'):
        data['MASK'] = data_bm.turn_on(data['MASK'], 'CRITCUBE')
    indx = hdu['EMLINE_GFLUX_MASK'].data[el['Ha-6564']].ravel()[uniq_indx] > 0
    if numpy.any(indx):
        data['MASK'][indx] = data_bm.turn_on(data['MASK'][indx], 'BADFLUX')
    indx = hdu['EMLINE_GEW_MASK'].data[el['Ha-6564']].ravel()[uniq_indx] > 0
    if numpy.any(indx):
        data['MASK'][indx] = data_bm.turn_on(data['MASK'][indx], 'BADEW')
    indx = (hdu['EMLINE_GVEL_MASK'].data.ravel()[uniq_indx] > 0) \
            | numpy.logical_not(hdu['EMLINE_GVEL_IVAR'].data.ravel()[uniq_indx] > 0)
    if numpy.any(indx):
        data['MASK'][indx] = data_bm.turn_on(data['MASK'][indx], 'BADVEL')
    indx = (hdu['EMLINE_GSIGMA_MASK'].data.ravel()[uniq_indx] > 0) \
            | numpy.logical_not(hdu['EMLINE_GSIGMA_IVAR'].data.ravel()[uniq_indx] > 0)
    if numpy.any(indx):
        data['MASK'][indx] = data_bm.turn_on(data['MASK'][indx], 'BADSIG')

    return data
Ejemplo n.º 8
0
def spotcheck_images(cube, plan, method_dir, ref_dir, qa_dir, fwhm=None):
    """
    Construct a QA plot for the PPXFFit results.

    Args:
        cube (:class:`~mangadap.datacube.datacube.DataCube`):
            Analyzed data cube
        plan (:obj:`dict`, :class:`~mangadap.par.parset.ParSet`):
            Object with analysis plan keywords.
        method_dir (`Path`_):
            Top-level "method" directory with all the DAP files.
        ref_dir (`Path`_):
            Directory with all the DAP reference files.
        qa_dir (`Path`_):
            Directory for the QA figures
        fwhm (:obj:`float`, optional):
            The FWHM in arcsec of the beam.  If None, no beam included in the
            plot.
    """
    # Check that the paths exists
    if not method_dir.exists():
        raise NotADirectoryError(
            f'{method_dir} does not exist; run the DAP first!')
    if not ref_dir.exists():
        raise NotADirectoryError(
            f'{ref_dir} does not exist; run the DAP first!')
    if not qa_dir.exists():
        qa_dir.mkdir(parents=True)

    # Get the name of the output file
    ofile = qa_dir / f'{cube.output_root}-MAPS-{plan["key"]}-spotcheck.png'

    bm = dapfits.DAPMapsBitMask()

    _, directory, file = dapfits.default_paths(cube,
                                               method=plan['key'],
                                               output_path=method_dir)
    ifile = directory / file
    if not ifile.exists():
        raise FileNotFoundError(f'No file: {ifile}')

    print(f'Reading: {ifile}')
    hdu = fits.open(str(ifile))

    # Check everything is finite
    num_ext = len(hdu)
    for i in range(num_ext):
        if hdu[i].data is None:
            continue
        if not numpy.all(numpy.isfinite(hdu[i].data)):
            raise ValueError(f'HDU {hdu[i].name} contains infs or NaNs!')

    # Build the column dictionaries
    emline = channel_dictionary(hdu, 'EMLINE_GFLUX')
    specindex = channel_dictionary(hdu, 'SPECINDEX')

    extent = map_extent(hdu, 'SPX_MFLUX')

    # Get the data to plot
    spxflx = numpy.ma.MaskedArray(hdu['SPX_MFLUX'].data.copy())
    spxsnr = numpy.ma.MaskedArray(hdu['SPX_SNR'].data.copy())
    binid = numpy.ma.MaskedArray(hdu['BINID'].data.copy(),
                                 mask=hdu['BINID'].data < 0)
    binsnr = numpy.ma.MaskedArray(hdu['BIN_SNR'].data.copy(),
                                  mask=hdu['BIN_MFLUX_MASK'].data > 0)

    # 68% growth of the absolute value of the fractional residuals
    scfres = numpy.ma.MaskedArray(
        hdu['STELLAR_FOM'].data.copy()[3, :, :],
        mask=numpy.invert(hdu['STELLAR_FOM'].data[3, :, :] > 0))
    # Reduced chi-square
    scrchi = numpy.ma.MaskedArray(
        hdu['STELLAR_FOM'].data.copy()[2, :, :],
        mask=numpy.invert(hdu['STELLAR_FOM'].data[2, :, :] > 0))

    strvel = numpy.ma.MaskedArray(hdu['STELLAR_VEL'].data.copy(),
                                  mask=bm.flagged(hdu['STELLAR_VEL_MASK'].data,
                                                  'DONOTUSE'))
    ustrvel = numpy.ma.MaskedArray(hdu['STELLAR_VEL'].data.copy(),
                                   mask=numpy.invert(
                                       bm.flagged(hdu['STELLAR_VEL_MASK'].data,
                                                  'UNRELIABLE')))
    ustrvel[numpy.invert(numpy.ma.getmaskarray(ustrvel))] = 0.0
    strsig = numpy.ma.MaskedArray(hdu['STELLAR_SIGMA'].data.copy(),
                                  mask=bm.flagged(
                                      hdu['STELLAR_SIGMA_MASK'].data,
                                      'DONOTUSE'))
    ustrsig = numpy.ma.MaskedArray(hdu['STELLAR_SIGMA'].data.copy(),
                                   mask=numpy.invert(
                                       bm.flagged(
                                           hdu['STELLAR_SIGMA_MASK'].data,
                                           'UNRELIABLE')))
    ustrsig[numpy.invert(numpy.ma.getmaskarray(ustrsig))] = 0.0

    hasflx = numpy.ma.MaskedArray(
        hdu['EMLINE_SFLUX'].data.copy()[emline['Ha-6564'], :, :],
        mask=bm.flagged(hdu['EMLINE_SFLUX_MASK'].data[emline['Ha-6564'], :, :],
                        'DONOTUSE'))
    uhasflx = numpy.ma.MaskedArray(
        hdu['EMLINE_SFLUX'].data.copy()[emline['Ha-6564'], :, :],
        mask=numpy.invert(
            bm.flagged(hdu['EMLINE_SFLUX_MASK'].data[emline['Ha-6564'], :, :],
                       'UNRELIABLE')))
    uhasflx[numpy.invert(numpy.ma.getmaskarray(uhasflx))] = 0.0
    hagflx = numpy.ma.MaskedArray(
        hdu['EMLINE_GFLUX'].data.copy()[emline['Ha-6564'], :, :],
        mask=bm.flagged(hdu['EMLINE_GFLUX_MASK'].data[emline['Ha-6564'], :, :],
                        'DONOTUSE'))
    uhagflx = numpy.ma.MaskedArray(
        hdu['EMLINE_GFLUX'].data.copy()[emline['Ha-6564'], :, :],
        mask=numpy.invert(
            bm.flagged(hdu['EMLINE_GFLUX_MASK'].data[emline['Ha-6564'], :, :],
                       'UNRELIABLE')))
    uhagflx[numpy.invert(numpy.ma.getmaskarray(uhagflx))] = 0.0
    hagvel = numpy.ma.MaskedArray(
        hdu['EMLINE_GVEL'].data.copy()[emline['Ha-6564'], :, :],
        mask=bm.flagged(hdu['EMLINE_GVEL_MASK'].data[emline['Ha-6564'], :, :],
                        'DONOTUSE'))
    uhagvel = numpy.ma.MaskedArray(
        hdu['EMLINE_GVEL'].data.copy()[emline['Ha-6564'], :, :],
        mask=numpy.invert(
            bm.flagged(hdu['EMLINE_GVEL_MASK'].data[emline['Ha-6564'], :, :],
                       'UNRELIABLE')))
    uhagvel[numpy.invert(numpy.ma.getmaskarray(uhagvel))] = 0.0
    hagsig = numpy.ma.MaskedArray(
        hdu['EMLINE_GSIGMA'].data.copy()[emline['Ha-6564'], :, :],
        mask=bm.flagged(
            hdu['EMLINE_GSIGMA_MASK'].data[emline['Ha-6564'], :, :],
            'DONOTUSE'))
    uhagsig = numpy.ma.MaskedArray(
        hdu['EMLINE_GSIGMA'].data.copy()[emline['Ha-6564'], :, :],
        mask=numpy.invert(
            bm.flagged(hdu['EMLINE_GSIGMA_MASK'].data[emline['Ha-6564'], :, :],
                       'UNRELIABLE')))
    uhagsig[numpy.invert(numpy.ma.getmaskarray(uhagsig))] = 0.0

    hbsflx = numpy.ma.MaskedArray(
        hdu['EMLINE_SFLUX'].data.copy()[emline['Hb-4862'], :, :],
        mask=bm.flagged(hdu['EMLINE_SFLUX_MASK'].data[emline['Hb-4862'], :, :],
                        'DONOTUSE'))
    uhbsflx = numpy.ma.MaskedArray(
        hdu['EMLINE_SFLUX'].data.copy()[emline['Hb-4862'], :, :],
        mask=numpy.invert(
            bm.flagged(hdu['EMLINE_SFLUX_MASK'].data[emline['Hb-4862'], :, :],
                       'UNRELIABLE')))
    uhbsflx[numpy.invert(numpy.ma.getmaskarray(uhbsflx))] = 0.0
    hbgflx = numpy.ma.MaskedArray(
        hdu['EMLINE_GFLUX'].data.copy()[emline['Hb-4862'], :, :],
        mask=bm.flagged(hdu['EMLINE_GFLUX_MASK'].data[emline['Hb-4862'], :, :],
                        'DONOTUSE'))
    uhbgflx = numpy.ma.MaskedArray(
        hdu['EMLINE_GFLUX'].data.copy()[emline['Hb-4862'], :, :],
        mask=numpy.invert(
            bm.flagged(hdu['EMLINE_GFLUX_MASK'].data[emline['Hb-4862'], :, :],
                       'UNRELIABLE')))
    uhbgflx[numpy.invert(numpy.ma.getmaskarray(uhbgflx))] = 0.0

    specindex_available = True
    try:
        if hdu['SPECINDEX'].data is None:
            pass
    except:
        warnings.warn('No spectral indices in maps file.')
        specindex_available = False
    if specindex_available:
        d4000 = numpy.ma.MaskedArray(
            hdu['SPECINDEX'].data.copy()[specindex['D4000'], :, :],
            mask=bm.flagged(
                hdu['SPECINDEX_MASK'].data[specindex['D4000'], :, :],
                'DONOTUSE'))
        ud4000 = numpy.ma.MaskedArray(
            hdu['SPECINDEX'].data.copy()[specindex['D4000'], :, :],
            mask=numpy.invert(
                bm.flagged(
                    hdu['SPECINDEX_MASK'].data[specindex['D4000'], :, :],
                    'UNRELIABLE')))
        ud4000[numpy.invert(numpy.ma.getmaskarray(ud4000))] = 0.0
        dn4000 = numpy.ma.MaskedArray(
            hdu['SPECINDEX'].data.copy()[specindex['Dn4000'], :, :],
            mask=bm.flagged(
                hdu['SPECINDEX_MASK'].data[specindex['Dn4000'], :, :],
                'DONOTUSE'))
        udn4000 = numpy.ma.MaskedArray(
            hdu['SPECINDEX'].data.copy()[specindex['Dn4000'], :, :],
            mask=numpy.invert(
                bm.flagged(
                    hdu['SPECINDEX_MASK'].data[specindex['Dn4000'], :, :],
                    'UNRELIABLE')))
        udn4000[numpy.invert(numpy.ma.getmaskarray(udn4000))] = 0.0
    else:
        output_shape = spxflx.shape
        d4000 = numpy.ma.masked_all(output_shape)
        ud4000 = numpy.ma.masked_all(output_shape)
        dn4000 = numpy.ma.masked_all(output_shape)
        udn4000 = numpy.ma.masked_all(output_shape)

    # Get the limits to apply
    x_order = 1 if extent[0] < extent[1] else -1
    Dx = x_order * (extent[1] - extent[0])
    y_order = 1 if extent[2] < extent[3] else -1
    Dy = y_order * (extent[3] - extent[2])
    # Force the image panels to be square; assumes extent has the same units in
    # both dimensions.
    D = max(Dx, Dy)

    x_lim = (extent[0] + extent[1]) / 2 + D * x_order * numpy.array([-1, 1
                                                                     ]) / 2
    y_lim = (extent[2] + extent[3]) / 2 + D * y_order * numpy.array([-1, 1
                                                                     ]) / 2

    flux_lim = numpy.power(10,
                           growth_lim(numpy.ma.log10(spxflx), 0.90, fac=1.05))
    t = numpy.ma.append(numpy.ma.log10(spxsnr), numpy.ma.log10(binsnr))
    snr_lim = numpy.power(10, growth_lim(t, 0.90, fac=1.05))
    bin_lim = [numpy.ma.amin(binid), numpy.ma.amax(binid)]

    res_lim = numpy.power(10, growth_lim(numpy.ma.log10(scfres),
                                         0.90,
                                         fac=1.05))
    chi_lim = growth_lim(scrchi, 0.90, fac=1.05)
    t = numpy.ma.append(strvel, hagvel)
    vel_lim = growth_lim(t, 0.85, fac=1.10, midpoint=0.0)
    if vel_lim[0] < -350:
        vel_lim[0] = -350
    if vel_lim[1] > 350:
        vel_lim[1] = 350
    t = numpy.ma.append(numpy.ma.log10(strsig), numpy.ma.log10(hagsig))
    sig_lim = numpy.power(10, growth_lim(t, 0.90, fac=1.05))

    t = numpy.ma.append(
        numpy.ma.append(numpy.ma.log10(hasflx), numpy.ma.log10(hagflx)),
        numpy.ma.append(numpy.ma.log10(hbsflx), numpy.ma.log10(hbgflx)))
    #    t = numpy.ma.log10(t)
    hflx_lim = numpy.power(10, growth_lim(t, 0.95, fac=1.10))
    #    hflx_lim = [ -0.3, 2.2 ]
    t = numpy.ma.append(d4000, dn4000)
    #    d4000_lim = growth_lim(t, 0.90, 1.05)
    d4000_lim = [1.0, 2.5]

    font = {'size': 6}
    rc('font', **font)

    w, h = pyplot.figaspect(1)
    fig = pyplot.figure(figsize=(1.5 * w, 1.5 * h))

    dx = 0.22
    left = 0.05
    top = 0.94
    dw = 0.005

    snr_levels = [0.5, 1.0, 1.5, 2.0]

    ax = init_ax(fig, [left, top - dx, dx, dx])
    ax.set_xlim(x_lim)
    ax.set_ylim(y_lim)
    ax.xaxis.set_major_formatter(ticker.NullFormatter())
    cax = fig.add_axes([left + dx * 0.65, top - 0.07 * dx, 0.27 * dx, 0.01])
    cbticks = [flux_lim[0] * 1.1, flux_lim[1] / 1.1]
    masked_imshow(fig,
                  ax,
                  cax,
                  spxflx,
                  extent=extent,
                  norm=colors.LogNorm(vmin=flux_lim[0], vmax=flux_lim[1]),
                  cmap='YlGnBu_r',
                  zorder=4,
                  orientation='horizontal',
                  contour_data=numpy.ma.log10(spxsnr),
                  levels=snr_levels,
                  cbticks=cbticks,
                  cbformat=ticker.ScalarFormatter())
    if fwhm is not None:
        ax.add_patch(
            map_beam_patch(extent,
                           ax,
                           fwhm=fwhm,
                           facecolor='0.7',
                           edgecolor='k',
                           zorder=4))
    ax.text(0.99,
            0.05,
            r'g-band S (spx)',
            horizontalalignment='right',
            verticalalignment='center',
            transform=ax.transAxes)

    ax = init_ax(fig, [left + dx + dw, top - dx, dx, dx])
    ax.set_xlim(x_lim)
    ax.set_ylim(y_lim)
    ax.xaxis.set_major_formatter(ticker.NullFormatter())
    ax.yaxis.set_major_formatter(ticker.NullFormatter())
    cax = fig.add_axes(
        [left + dx + dw + dx * 0.65, top - 0.07 * dx, 0.27 * dx, 0.01])
    cbticks = [snr_lim[0] * 1.1, snr_lim[1] / 1.1]
    masked_imshow(fig,
                  ax,
                  cax,
                  spxsnr,
                  extent=extent,
                  norm=colors.LogNorm(vmin=snr_lim[0], vmax=snr_lim[1]),
                  cmap='YlGnBu_r',
                  zorder=4,
                  orientation='horizontal',
                  contour_data=numpy.ma.log10(spxsnr),
                  levels=snr_levels,
                  cbticks=cbticks,
                  cbformat=ticker.ScalarFormatter())  #'%.0f')
    if fwhm is not None:
        ax.add_patch(
            map_beam_patch(extent,
                           ax,
                           fwhm=fwhm,
                           facecolor='0.7',
                           edgecolor='k',
                           zorder=4))
    ax.text(0.99,
            0.05,
            r'g-band S/N (spx)',
            horizontalalignment='right',
            verticalalignment='center',
            transform=ax.transAxes)

    #    ax.text(1.0, 1.1, r'{0}-{1}; {2}'.format(plate,ifudesign, hdu['PRIMARY'].header['MANGAID']),
    #            horizontalalignment='center', verticalalignment='center', transform=ax.transAxes,
    #            fontsize=20)
    ax.text(1.0,
            1.1,
            f'{cube.name}; {plan["key"]}',
            ha='center',
            va='center',
            transform=ax.transAxes,
            fontsize=20)

    ax = init_ax(fig, [left + 2 * dx + 2 * dw, top - dx, dx, dx])
    ax.set_xlim(x_lim)
    ax.set_ylim(y_lim)
    ax.xaxis.set_major_formatter(ticker.NullFormatter())
    ax.yaxis.set_major_formatter(ticker.NullFormatter())
    cax = fig.add_axes(
        [left + 2 * dx + 2 * dw + dx * 0.65, top - 0.07 * dx, 0.27 * dx, 0.01])
    masked_imshow(fig,
                  ax,
                  cax,
                  binid[0, :, :],
                  extent=extent,
                  vmin=bin_lim[0],
                  vmax=bin_lim[1],
                  cmap='CMRmap',
                  zorder=4,
                  orientation='horizontal',
                  contour_data=numpy.ma.log10(spxsnr),
                  levels=snr_levels,
                  cbformat=ticker.ScalarFormatter(),
                  cbticks=bin_lim)
    if fwhm is not None:
        ax.add_patch(
            map_beam_patch(extent,
                           ax,
                           fwhm=fwhm,
                           facecolor='0.7',
                           edgecolor='k',
                           zorder=4))
    ax.text(0.99,
            0.05,
            r'bin ID',
            horizontalalignment='right',
            verticalalignment='center',
            transform=ax.transAxes)

    ax = init_ax(fig, [left + 3 * dx + 3 * dw, top - dx, dx, dx])
    ax.set_xlim(x_lim)
    ax.set_ylim(y_lim)
    ax.xaxis.set_major_formatter(ticker.NullFormatter())
    ax.yaxis.set_major_formatter(ticker.NullFormatter())
    cax = fig.add_axes(
        [left + 3 * dx + 3 * dw + dx * 0.65, top - 0.07 * dx, 0.27 * dx, 0.01])
    cbticks = [snr_lim[0] * 1.1, snr_lim[1] / 1.1]
    masked_imshow(fig,
                  ax,
                  cax,
                  binsnr,
                  extent=extent,
                  norm=colors.LogNorm(vmin=snr_lim[0], vmax=snr_lim[1]),
                  cmap='YlGnBu_r',
                  zorder=4,
                  orientation='horizontal',
                  contour_data=numpy.ma.log10(spxsnr),
                  levels=snr_levels,
                  cbticks=cbticks,
                  cbformat=ticker.ScalarFormatter())  #'%.0f')
    if fwhm is not None:
        ax.add_patch(
            map_beam_patch(extent,
                           ax,
                           fwhm=fwhm,
                           facecolor='0.7',
                           edgecolor='k',
                           zorder=4))
    ax.text(0.99,
            0.05,
            r'g-band S/N (bin)',
            horizontalalignment='right',
            verticalalignment='center',
            transform=ax.transAxes)

    ax = init_ax(fig, [left, top - 2 * dx - dw, dx, dx])
    ax.set_xlim(x_lim)
    ax.set_ylim(y_lim)
    ax.xaxis.set_major_formatter(ticker.NullFormatter())
    cax = fig.add_axes(
        [left + dx * 0.65, top - dx - dw - 0.07 * dx, 0.27 * dx, 0.01])
    cbticks = [res_lim[0] * 1.1, res_lim[1] / 1.1]
    masked_imshow(fig,
                  ax,
                  cax,
                  scfres,
                  extent=extent,
                  norm=colors.LogNorm(vmin=res_lim[0], vmax=res_lim[1]),
                  cmap='inferno',
                  zorder=4,
                  orientation='horizontal',
                  contour_data=numpy.ma.log10(spxsnr),
                  levels=snr_levels,
                  cbticks=cbticks,
                  cbformat=ticker.ScalarFormatter())  #'%.0f')
    if fwhm is not None:
        ax.add_patch(
            map_beam_patch(extent,
                           ax,
                           fwhm=fwhm,
                           facecolor='0.7',
                           edgecolor='k',
                           zorder=4))
    ax.text(0.99,
            0.05,
            r'pPXF Frac. Resid.',
            horizontalalignment='right',
            verticalalignment='center',
            transform=ax.transAxes)

    ax = init_ax(fig, [left + dx + dw, top - 2 * dx - dw, dx, dx])
    ax.set_xlim(x_lim)
    ax.set_ylim(y_lim)
    ax.xaxis.set_major_formatter(ticker.NullFormatter())
    ax.yaxis.set_major_formatter(ticker.NullFormatter())
    cax = fig.add_axes([
        left + dx + dw + dx * 0.65, top - dx - dw - 0.07 * dx, 0.27 * dx, 0.01
    ])
    cbticks = [
        numpy.round(chi_lim[0] + 0.01, decimals=2),
        numpy.round(chi_lim[1] - 0.01, decimals=2)
    ]
    masked_imshow(fig,
                  ax,
                  cax,
                  scrchi,
                  extent=extent,
                  vmin=chi_lim[0],
                  vmax=chi_lim[1],
                  cmap='inferno',
                  zorder=4,
                  orientation='horizontal',
                  contour_data=numpy.ma.log10(spxsnr),
                  levels=snr_levels,
                  cbticks=cbticks,
                  cbformat=ticker.ScalarFormatter())  #'%.0f')
    if fwhm is not None:
        ax.add_patch(
            map_beam_patch(extent,
                           ax,
                           fwhm=fwhm,
                           facecolor='0.7',
                           edgecolor='k',
                           zorder=4))
    ax.text(0.99,
            0.05,
            r'${\rm pPXF}\ \chi^2_\nu$',
            horizontalalignment='right',
            verticalalignment='center',
            transform=ax.transAxes)

    ax = init_ax(fig, [left + 2 * dx + 2 * dw, top - 2 * dx - dw, dx, dx])
    ax.set_xlim(x_lim)
    ax.set_ylim(y_lim)
    ax.xaxis.set_major_formatter(ticker.NullFormatter())
    ax.yaxis.set_major_formatter(ticker.NullFormatter())
    cax = fig.add_axes([
        left + 2 * dx + 2 * dw + dx * 0.65, top - dx - dw - 0.07 * dx,
        0.27 * dx, 0.01
    ])
    cbticks = [vel_lim[0] / 1.1, 0.0, vel_lim[1] / 1.1]
    masked_imshow(fig,
                  ax,
                  cax,
                  strvel,
                  extent=extent,
                  vmin=vel_lim[0],
                  vmax=vel_lim[1],
                  cmap='RdBu_r',
                  zorder=4,
                  orientation='horizontal',
                  contour_data=numpy.ma.log10(spxsnr),
                  levels=snr_levels,
                  cbticks=cbticks,
                  cbformat=ticker.ScalarFormatter())  #'%.0f')
    if fwhm is not None:
        ax.add_patch(
            map_beam_patch(extent,
                           ax,
                           fwhm=fwhm,
                           facecolor='0.7',
                           edgecolor='k',
                           zorder=4))
    ax.text(0.99,
            0.05,
            r'$V_\ast$',
            horizontalalignment='right',
            verticalalignment='center',
            transform=ax.transAxes)

    ax = init_ax(fig, [left + 3 * dx + 3 * dw, top - 2 * dx - dw, dx, dx])
    ax.set_xlim(x_lim)
    ax.set_ylim(y_lim)
    ax.xaxis.set_major_formatter(ticker.NullFormatter())
    ax.yaxis.set_major_formatter(ticker.NullFormatter())
    cax = fig.add_axes([
        left + 3 * dx + 3 * dw + dx * 0.65, top - dx - dw - 0.07 * dx,
        0.27 * dx, 0.01
    ])
    cbticks = [
        sig_lim[0] * 1.1,
        numpy.power(10, numpy.mean(numpy.log10(sig_lim))), sig_lim[1] / 1.1
    ]
    masked_imshow(fig,
                  ax,
                  cax,
                  strsig,
                  extent=extent,
                  norm=colors.LogNorm(vmin=sig_lim[0], vmax=sig_lim[1]),
                  cmap='viridis',
                  zorder=4,
                  orientation='horizontal',
                  contour_data=numpy.ma.log10(spxsnr),
                  levels=snr_levels,
                  cbticks=cbticks,
                  cbformat=ticker.ScalarFormatter())  #'%.0f')
    if fwhm is not None:
        ax.add_patch(
            map_beam_patch(extent,
                           ax,
                           fwhm=fwhm,
                           facecolor='0.7',
                           edgecolor='k',
                           zorder=4))
    ax.text(0.99,
            0.05,
            r'$\sigma_\ast$',
            horizontalalignment='right',
            verticalalignment='center',
            transform=ax.transAxes)

    ax = init_ax(fig, [left, top - 3 * dx - 2 * dw, dx, dx])
    ax.set_xlim(x_lim)
    ax.set_ylim(y_lim)
    ax.xaxis.set_major_formatter(ticker.NullFormatter())
    cax = fig.add_axes(
        [left + dx * 0.65, top - 2 * dx - 2 * dw - 0.07 * dx, 0.27 * dx, 0.01])
    cbticks = [hflx_lim[0] * 1.1, hflx_lim[1] / 1.1]
    masked_imshow(fig,
                  ax,
                  cax,
                  hasflx,
                  extent=extent,
                  norm=colors.LogNorm(vmin=hflx_lim[0], vmax=hflx_lim[1]),
                  cmap='inferno',
                  zorder=4,
                  orientation='horizontal',
                  contour_data=numpy.ma.log10(spxsnr),
                  levels=snr_levels,
                  cbticks=cbticks,
                  cbformat=ticker.ScalarFormatter())  #'%.0f')
    if fwhm is not None:
        ax.add_patch(
            map_beam_patch(extent,
                           ax,
                           fwhm=fwhm,
                           facecolor='0.7',
                           edgecolor='k',
                           zorder=4))
    ax.text(0.99,
            0.05,
            r'${\rm H}\alpha\ {\rm flux}$ (sum)',
            horizontalalignment='right',
            verticalalignment='center',
            transform=ax.transAxes)

    ax = init_ax(fig, [left + dx + dw, top - 3 * dx - 2 * dw, dx, dx])
    ax.set_xlim(x_lim)
    ax.set_ylim(y_lim)
    ax.xaxis.set_major_formatter(ticker.NullFormatter())
    ax.yaxis.set_major_formatter(ticker.NullFormatter())
    cax = fig.add_axes([
        left + dx + dw + dx * 0.65, top - 2 * dx - 2 * dw - 0.07 * dx,
        0.27 * dx, 0.01
    ])
    cbticks = [hflx_lim[0] * 1.1, hflx_lim[1] / 1.1]
    masked_imshow(fig,
                  ax,
                  cax,
                  hagflx,
                  extent=extent,
                  norm=colors.LogNorm(vmin=hflx_lim[0], vmax=hflx_lim[1]),
                  cmap='inferno',
                  zorder=4,
                  orientation='horizontal',
                  contour_data=numpy.ma.log10(spxsnr),
                  levels=snr_levels,
                  cbticks=cbticks,
                  cbformat=ticker.ScalarFormatter())  #'%.0f')
    if fwhm is not None:
        ax.add_patch(
            map_beam_patch(extent,
                           ax,
                           fwhm=fwhm,
                           facecolor='0.7',
                           edgecolor='k',
                           zorder=4))
    ax.text(0.99,
            0.05,
            r'${\rm H}\alpha\ {\rm flux}$ (Gauss)',
            horizontalalignment='right',
            verticalalignment='center',
            transform=ax.transAxes)

    ax = init_ax(fig, [left + 2 * dx + 2 * dw, top - 3 * dx - 2 * dw, dx, dx])
    ax.set_xlim(x_lim)
    ax.set_ylim(y_lim)
    ax.xaxis.set_major_formatter(ticker.NullFormatter())
    ax.yaxis.set_major_formatter(ticker.NullFormatter())
    cax = fig.add_axes([
        left + 2 * dx + 2 * dw + dx * 0.65, top - 2 * dx - 2 * dw - 0.07 * dx,
        0.27 * dx, 0.01
    ])
    cbticks = [vel_lim[0] / 1.1, 0.0, vel_lim[1] / 1.1]
    masked_imshow(fig,
                  ax,
                  cax,
                  hagvel,
                  extent=extent,
                  vmin=vel_lim[0],
                  vmax=vel_lim[1],
                  cmap='RdBu_r',
                  zorder=4,
                  orientation='horizontal',
                  contour_data=numpy.ma.log10(spxsnr),
                  levels=snr_levels,
                  cbticks=cbticks,
                  cbformat=ticker.ScalarFormatter())  #'%.0f')
    if fwhm is not None:
        ax.add_patch(
            map_beam_patch(extent,
                           ax,
                           fwhm=fwhm,
                           facecolor='0.7',
                           edgecolor='k',
                           zorder=4))
    ax.text(0.99,
            0.05,
            r'$V_{{\rm H}\alpha}$',
            horizontalalignment='right',
            verticalalignment='center',
            transform=ax.transAxes)

    ax = init_ax(fig, [left + 3 * dx + 3 * dw, top - 3 * dx - 2 * dw, dx, dx])
    ax.set_xlim(x_lim)
    ax.set_ylim(y_lim)
    ax.xaxis.set_major_formatter(ticker.NullFormatter())
    ax.yaxis.set_major_formatter(ticker.NullFormatter())
    cax = fig.add_axes([
        left + 3 * dx + 3 * dw + dx * 0.65, top - 2 * dx - 2 * dw - 0.07 * dx,
        0.27 * dx, 0.01
    ])
    cbticks = [
        sig_lim[0] * 1.1,
        numpy.power(10, numpy.mean(numpy.log10(sig_lim))), sig_lim[1] / 1.1
    ]
    masked_imshow(fig,
                  ax,
                  cax,
                  hagsig,
                  extent=extent,
                  norm=colors.LogNorm(vmin=sig_lim[0], vmax=sig_lim[1]),
                  cmap='viridis',
                  zorder=4,
                  orientation='horizontal',
                  contour_data=numpy.ma.log10(spxsnr),
                  levels=snr_levels,
                  cbticks=cbticks,
                  cbformat=ticker.ScalarFormatter())  #'%.0f')
    if fwhm is not None:
        ax.add_patch(
            map_beam_patch(extent,
                           ax,
                           fwhm=fwhm,
                           facecolor='0.7',
                           edgecolor='k',
                           zorder=4))
    ax.text(0.99,
            0.05,
            r'$\sigma_{{\rm H}\alpha}$',
            horizontalalignment='right',
            verticalalignment='center',
            transform=ax.transAxes)

    ax = init_ax(fig, [left, top - 4 * dx - 3 * dw, dx, dx])
    ax.set_xlim(x_lim)
    ax.set_ylim(y_lim)
    cax = fig.add_axes(
        [left + dx * 0.65, top - 3 * dx - 3 * dw - 0.07 * dx, 0.27 * dx, 0.01])
    cbticks = [hflx_lim[0] * 1.1, hflx_lim[1] / 1.1]
    masked_imshow(fig,
                  ax,
                  cax,
                  hbsflx,
                  extent=extent,
                  norm=colors.LogNorm(vmin=hflx_lim[0], vmax=hflx_lim[1]),
                  cmap='inferno',
                  zorder=4,
                  orientation='horizontal',
                  contour_data=numpy.ma.log10(spxsnr),
                  levels=snr_levels,
                  cbticks=cbticks,
                  cbformat=ticker.ScalarFormatter())  #'%.0f')
    if fwhm is not None:
        ax.add_patch(
            map_beam_patch(extent,
                           ax,
                           fwhm=fwhm,
                           facecolor='0.7',
                           edgecolor='k',
                           zorder=4))
    ax.text(0.99,
            0.05,
            r'${\rm H}\beta\ {\rm flux}$ (sum)',
            horizontalalignment='right',
            verticalalignment='center',
            transform=ax.transAxes)

    ax = init_ax(fig, [left + dx + dw, top - 4 * dx - 3 * dw, dx, dx])
    ax.set_xlim(x_lim)
    ax.set_ylim(y_lim)
    ax.yaxis.set_major_formatter(ticker.NullFormatter())
    cax = fig.add_axes([
        left + dx + dw + dx * 0.65, top - 3 * dx - 3 * dw - 0.07 * dx,
        0.27 * dx, 0.01
    ])
    cbticks = [hflx_lim[0] * 1.1, hflx_lim[1] / 1.1]
    masked_imshow(fig,
                  ax,
                  cax,
                  hbgflx,
                  extent=extent,
                  norm=colors.LogNorm(vmin=hflx_lim[0], vmax=hflx_lim[1]),
                  cmap='inferno',
                  zorder=4,
                  orientation='horizontal',
                  contour_data=numpy.ma.log10(spxsnr),
                  levels=snr_levels,
                  cbticks=cbticks,
                  cbformat=ticker.ScalarFormatter())  #'%.0f')
    if fwhm is not None:
        ax.add_patch(
            map_beam_patch(extent,
                           ax,
                           fwhm=fwhm,
                           facecolor='0.7',
                           edgecolor='k',
                           zorder=4))
    ax.text(0.99,
            0.05,
            r'${\rm H}\beta\ {\rm flux}$ (Gauss)',
            horizontalalignment='right',
            verticalalignment='center',
            transform=ax.transAxes)

    ax = init_ax(fig, [left + 2 * dx + 2 * dw, top - 4 * dx - 3 * dw, dx, dx])
    ax.set_xlim(x_lim)
    ax.set_ylim(y_lim)
    ax.yaxis.set_major_formatter(ticker.NullFormatter())
    cax = fig.add_axes([
        left + 2 * dx + 2 * dw + dx * 0.65, top - 3 * dx - 3 * dw - 0.07 * dx,
        0.27 * dx, 0.01
    ])
    masked_imshow(fig,
                  ax,
                  cax,
                  d4000,
                  extent=extent,
                  vmin=d4000_lim[0],
                  vmax=d4000_lim[1],
                  cmap='RdBu_r',
                  zorder=4,
                  orientation='horizontal',
                  contour_data=numpy.ma.log10(spxsnr),
                  levels=snr_levels,
                  cbticks=d4000_lim,
                  cbformat=ticker.ScalarFormatter())
    if fwhm is not None:
        ax.add_patch(
            map_beam_patch(extent,
                           ax,
                           fwhm=fwhm,
                           facecolor='0.7',
                           edgecolor='k',
                           zorder=4))
    ax.text(0.99,
            0.05,
            r'D4000',
            horizontalalignment='right',
            verticalalignment='center',
            transform=ax.transAxes)

    ax = init_ax(fig, [left + 3 * dx + 3 * dw, top - 4 * dx - 3 * dw, dx, dx])
    ax.set_xlim(x_lim)
    ax.set_ylim(y_lim)
    ax.yaxis.set_major_formatter(ticker.NullFormatter())
    cax = fig.add_axes([
        left + 3 * dx + 3 * dw + dx * 0.65, top - 3 * dx - 3 * dw - 0.07 * dx,
        0.27 * dx, 0.01
    ])
    masked_imshow(fig,
                  ax,
                  cax,
                  dn4000,
                  extent=extent,
                  vmin=d4000_lim[0],
                  vmax=d4000_lim[1],
                  cmap='RdBu_r',
                  zorder=4,
                  orientation='horizontal',
                  contour_data=numpy.ma.log10(spxsnr),
                  levels=snr_levels,
                  cbticks=d4000_lim,
                  cbformat=ticker.ScalarFormatter())
    if fwhm is not None:
        ax.add_patch(
            map_beam_patch(extent,
                           ax,
                           fwhm=fwhm,
                           facecolor='0.7',
                           edgecolor='k',
                           zorder=4))
    ax.text(0.99,
            0.05,
            r'Dn4000',
            horizontalalignment='right',
            verticalalignment='center',
            transform=ax.transAxes)

    if ofile is not None:
        fig.canvas.print_figure(ofile, bbox_inches='tight')
        print('Writing: {0}'.format(ofile))
    else:
        pyplot.show()

    fig.clear()
    pyplot.close(fig)
Ejemplo n.º 9
0
def include_maps_data(tbl, maps_file, exclude_ancillary=False):
    qual_bm = DAPQualityBitMask()
    bm = DAPMapsBitMask()

    #    # Targeting bits
    #    sdssMaskbits = defaults.sdss_maskbits_file()
    #    mngtarg1_bm = BitMask.from_par_file(sdssMaskbits, 'MANGA_TARGET1')
    #    mngtarg3_bm = BitMask.from_par_file(sdssMaskbits, 'MANGA_TARGET3')

    with fits.open(maps_file) as hdu:
        # Check if the file was CRITICAL
        if qual_bm.flagged(hdu['PRIMARY'].header['DAPQUAL'], flag='DRPCRIT'):
            return 1
        if exclude_ancillary and hdu[0].header['MNGTARG1'] == 0:
            return 1

        d4000_bins = numpy.unique(tbl['D4000BIN'])
        sigma_bins = numpy.unique(tbl['SIGMABIN'])
        haew_bins = numpy.unique(tbl['HAEWBIN'])
        snr_bins = numpy.unique(tbl['SNRBIN'])
        nsigma = len(sigma_bins) - 1
        nd4000 = len(d4000_bins) - 1
        nhaew = len(haew_bins) - 1
        nsnr = len(snr_bins) - 1

        el = channel_dictionary(hdu, 'EMLINE_GFLUX')
        si = channel_dictionary(hdu, 'SPECINDEX')

        plt, ifu = map(lambda x: int(x),
                       os.path.split(maps_file)[1].split('-')[1:3])

        # Input redshift
        z = hdu['PRIMARY'].header['SCINPVEL'] / astropy.constants.c.to(
            'km/s').value

        # Stellar-kinematics binning map
        binid, bin_indx = map(
            lambda x: x[1:],
            numpy.unique(hdu['BINID'].data[1, :, :].ravel(),
                         return_index=True))

        # Get the D4000, H-alpha EW, and sigma values with S/N greater
        # than one and unmasked
        good_snr = hdu['SPX_SNR'].data.ravel() > 1
        good_haew = numpy.logical_not(
            bm.flagged(hdu['EMLINE_GEW_MASK'].data[el['Ha-6564']].ravel(),
                       flag='DONOTUSE'))
        good_d4000 = numpy.logical_not(
            bm.flagged(hdu['SPECINDEX_MASK'].data[si['D4000']].ravel(),
                       flag='DONOTUSE'))
        good_sigma = numpy.logical_not(
            bm.flagged(hdu['STELLAR_SIGMA_MASK'].data.ravel(),
                       flag='DONOTUSE'))

        indx = (good_snr & good_haew & good_d4000 & good_sigma)[bin_indx]
        snr = hdu['SPX_SNR'].data.ravel()[bin_indx][indx]
        stvel = hdu['STELLAR_VEL'].data.ravel()[bin_indx][indx]
        sigma = hdu['STELLAR_SIGMA'].data.ravel()[bin_indx][indx]
        haanr = hdu['EMLINE_GANR'].data[el['Ha-6564']].ravel()[bin_indx][indx]
        havel = hdu['EMLINE_GVEL'].data[el['Ha-6564']].ravel()[bin_indx][indx]
        hasig = hdu['EMLINE_GSIGMA'].data[
            el['Ha-6564']].ravel()[bin_indx][indx]
        haew = hdu['EMLINE_GEW'].data[el['Ha-6564']].ravel()[bin_indx][indx]
        d4000 = hdu['SPECINDEX'].data[si['D4000']].ravel()[bin_indx][indx]
        binid = binid[indx]

        d4000_i = numpy.digitize(d4000, d4000_bins[1:-1])
        sigma_j = numpy.digitize(sigma, sigma_bins[1:-1])
        haew_k = numpy.digitize(haew, haew_bins[1:-1])
        snr_l = numpy.digitize(snr, snr_bins[1:-1])

        for i in range(nd4000):
            dindx = d4000_i == i
            for j in range(nsigma):
                sindx = sigma_j == j
                for k in range(nhaew):
                    hindx = haew_k == k
                    for l in range(nsnr):
                        nindx = snr_l == l

                        indx = dindx & sindx & hindx & nindx

                        nbin = numpy.sum(indx)
                        if nbin == 0:
                            continue

                        ii = i * nsigma * nhaew * nsnr + j * nhaew * nsnr + k * nsnr + l
                        tbl['NBIN'][ii] += nbin

                        _snr = snr[indx]
                        # Still find the highest S/N spectrum in each
                        # bin
                        m = numpy.argsort(_snr)[-1]
                        if _snr[m] < tbl['SNR'][ii]:
                            continue

                        tbl['PLT'][ii] = plt
                        tbl['IFU'][ii] = ifu
                        tbl['BIN'][ii] = binid[indx][m]
                        tbl['MNGTARG1'][ii] = int(hdu[0].header['MNGTARG1'])
                        tbl['MNGTARG3'][ii] = int(hdu[0].header['MNGTARG3'])
                        tbl['Z'][ii] = z
                        tbl['SNR'][ii] = snr[indx][m]
                        tbl['STZ'][ii] \
                            = stvel[indx][m]*(1+z)/astropy.constants.c.to('km/s').value + z
                        tbl['SIGMA'][ii] = sigma[indx][m]
                        tbl['HAANR'][ii] = haanr[indx][m]
                        tbl['HAZ'][ii] \
                            = havel[indx][m]*(1+z)/astropy.constants.c.to('km/s').value + z
                        tbl['HASIGMA'][ii] = hasig[indx][m]
                        tbl['HAEW'][ii] = haew[indx][m]
                        tbl['D4000'][ii] = d4000[indx][m]

    return 0
Ejemplo n.º 10
0
def spotcheck_images(analysis_path,
                     daptype,
                     plate,
                     ifudesign,
                     ofile=None,
                     drpver=None,
                     dapver=None):

    bm = DAPMapsBitMask()

    plan_dir = defaults.dap_method_path(daptype,
                                        plate=plate,
                                        ifudesign=ifudesign,
                                        drpver=drpver,
                                        dapver=dapver,
                                        analysis_path=analysis_path)
    ifile = os.path.join(
        plan_dir,
        'manga-{0}-{1}-MAPS-{2}.fits.gz'.format(plate, ifudesign, daptype))
    if not os.path.isfile(ifile):
        raise FileNotFoundError('No file: {0}'.format(ifile))

    print('Reading: {0}'.format(ifile))
    hdu = fits.open(ifile)

    # Check everything is finite
    num_ext = len(hdu)
    for i in range(num_ext):
        if hdu[i].data is None:
            continue
        if not numpy.all(numpy.isfinite(hdu[i].data)):
            raise ValueError('HDU {0} contains infs or NaNs!'.format(
                hdu[i].name))

    # Build the column dictionaries
    emline = channel_dictionary(hdu, 'EMLINE_GFLUX')
    specindex = channel_dictionary(hdu, 'SPECINDEX')

    extent = map_extent(hdu, 'SPX_MFLUX')

    # Get the data to plot
    spxflx = numpy.ma.MaskedArray(hdu['SPX_MFLUX'].data.copy())
    spxsnr = numpy.ma.MaskedArray(hdu['SPX_SNR'].data.copy())
    binid = numpy.ma.MaskedArray(hdu['BINID'].data.copy(),
                                 mask=hdu['BINID'].data < 0)
    binsnr = numpy.ma.MaskedArray(hdu['BIN_SNR'].data.copy(),
                                  mask=hdu['BIN_MFLUX_MASK'].data > 0)

    #    scfres = numpy.ma.MaskedArray(hdu['STELLAR_CONT_FRESID'].data.copy()[0,:,:],
    #                                  mask=numpy.invert(hdu['STELLAR_CONT_FRESID'].data[0,:,:] > 0))
    #                                  #bm.flagged(hdu['STELLAR_VEL_MASK'].data, 'DONOTUSE'))
    #    scrchi = numpy.ma.MaskedArray(hdu['STELLAR_CONT_RCHI2'].data.copy(),
    #                                  mask=numpy.invert(hdu['STELLAR_CONT_RCHI2'].data > 0))
    #                                  #mask=bm.flagged(hdu['STELLAR_VEL_MASK'].data, 'DONOTUSE'))

    # 68% growth of the absolute value of the fractional residuals
    scfres = numpy.ma.MaskedArray(
        hdu['STELLAR_FOM'].data.copy()[3, :, :],
        mask=numpy.invert(hdu['STELLAR_FOM'].data[3, :, :] > 0))
    # Reduced chi-square
    scrchi = numpy.ma.MaskedArray(
        hdu['STELLAR_FOM'].data.copy()[2, :, :],
        mask=numpy.invert(hdu['STELLAR_FOM'].data[2, :, :] > 0))

    strvel = numpy.ma.MaskedArray(hdu['STELLAR_VEL'].data.copy(),
                                  mask=bm.flagged(hdu['STELLAR_VEL_MASK'].data,
                                                  'DONOTUSE'))
    ustrvel = numpy.ma.MaskedArray(hdu['STELLAR_VEL'].data.copy(),
                                   mask=numpy.invert(
                                       bm.flagged(hdu['STELLAR_VEL_MASK'].data,
                                                  'UNRELIABLE')))
    ustrvel[numpy.invert(numpy.ma.getmaskarray(ustrvel))] = 0.0
    strsig = numpy.ma.MaskedArray(hdu['STELLAR_SIGMA'].data.copy(),
                                  mask=bm.flagged(
                                      hdu['STELLAR_SIGMA_MASK'].data,
                                      'DONOTUSE'))
    ustrsig = numpy.ma.MaskedArray(hdu['STELLAR_SIGMA'].data.copy(),
                                   mask=numpy.invert(
                                       bm.flagged(
                                           hdu['STELLAR_SIGMA_MASK'].data,
                                           'UNRELIABLE')))
    ustrsig[numpy.invert(numpy.ma.getmaskarray(ustrsig))] = 0.0

    hasflx = numpy.ma.MaskedArray(
        hdu['EMLINE_SFLUX'].data.copy()[emline['Ha-6564'], :, :],
        mask=bm.flagged(hdu['EMLINE_SFLUX_MASK'].data[emline['Ha-6564'], :, :],
                        'DONOTUSE'))
    uhasflx = numpy.ma.MaskedArray(
        hdu['EMLINE_SFLUX'].data.copy()[emline['Ha-6564'], :, :],
        mask=numpy.invert(
            bm.flagged(hdu['EMLINE_SFLUX_MASK'].data[emline['Ha-6564'], :, :],
                       'UNRELIABLE')))
    uhasflx[numpy.invert(numpy.ma.getmaskarray(uhasflx))] = 0.0
    hagflx = numpy.ma.MaskedArray(
        hdu['EMLINE_GFLUX'].data.copy()[emline['Ha-6564'], :, :],
        mask=bm.flagged(hdu['EMLINE_GFLUX_MASK'].data[emline['Ha-6564'], :, :],
                        'DONOTUSE'))
    uhagflx = numpy.ma.MaskedArray(
        hdu['EMLINE_GFLUX'].data.copy()[emline['Ha-6564'], :, :],
        mask=numpy.invert(
            bm.flagged(hdu['EMLINE_GFLUX_MASK'].data[emline['Ha-6564'], :, :],
                       'UNRELIABLE')))
    uhagflx[numpy.invert(numpy.ma.getmaskarray(uhagflx))] = 0.0
    hagvel = numpy.ma.MaskedArray(
        hdu['EMLINE_GVEL'].data.copy()[emline['Ha-6564'], :, :],
        mask=bm.flagged(hdu['EMLINE_GVEL_MASK'].data[emline['Ha-6564'], :, :],
                        'DONOTUSE'))
    uhagvel = numpy.ma.MaskedArray(
        hdu['EMLINE_GVEL'].data.copy()[emline['Ha-6564'], :, :],
        mask=numpy.invert(
            bm.flagged(hdu['EMLINE_GVEL_MASK'].data[emline['Ha-6564'], :, :],
                       'UNRELIABLE')))
    uhagvel[numpy.invert(numpy.ma.getmaskarray(uhagvel))] = 0.0
    hagsig = numpy.ma.MaskedArray(
        hdu['EMLINE_GSIGMA'].data.copy()[emline['Ha-6564'], :, :],
        mask=bm.flagged(
            hdu['EMLINE_GSIGMA_MASK'].data[emline['Ha-6564'], :, :],
            'DONOTUSE'))
    uhagsig = numpy.ma.MaskedArray(
        hdu['EMLINE_GSIGMA'].data.copy()[emline['Ha-6564'], :, :],
        mask=numpy.invert(
            bm.flagged(hdu['EMLINE_GSIGMA_MASK'].data[emline['Ha-6564'], :, :],
                       'UNRELIABLE')))
    uhagsig[numpy.invert(numpy.ma.getmaskarray(uhagsig))] = 0.0

    hbsflx = numpy.ma.MaskedArray(
        hdu['EMLINE_SFLUX'].data.copy()[emline['Hb-4862'], :, :],
        mask=bm.flagged(hdu['EMLINE_SFLUX_MASK'].data[emline['Hb-4862'], :, :],
                        'DONOTUSE'))
    uhbsflx = numpy.ma.MaskedArray(
        hdu['EMLINE_SFLUX'].data.copy()[emline['Hb-4862'], :, :],
        mask=numpy.invert(
            bm.flagged(hdu['EMLINE_SFLUX_MASK'].data[emline['Hb-4862'], :, :],
                       'UNRELIABLE')))
    uhbsflx[numpy.invert(numpy.ma.getmaskarray(uhbsflx))] = 0.0
    hbgflx = numpy.ma.MaskedArray(
        hdu['EMLINE_GFLUX'].data.copy()[emline['Hb-4862'], :, :],
        mask=bm.flagged(hdu['EMLINE_GFLUX_MASK'].data[emline['Hb-4862'], :, :],
                        'DONOTUSE'))
    uhbgflx = numpy.ma.MaskedArray(
        hdu['EMLINE_GFLUX'].data.copy()[emline['Hb-4862'], :, :],
        mask=numpy.invert(
            bm.flagged(hdu['EMLINE_GFLUX_MASK'].data[emline['Hb-4862'], :, :],
                       'UNRELIABLE')))
    uhbgflx[numpy.invert(numpy.ma.getmaskarray(uhbgflx))] = 0.0

    specindex_available = True
    try:
        if hdu['SPECINDEX'].data is None:
            pass
    except:
        warnings.warn('No spectral indices in maps file.')
        specindex_available = False
    if specindex_available:
        d4000 = numpy.ma.MaskedArray(
            hdu['SPECINDEX'].data.copy()[specindex['D4000'], :, :],
            mask=bm.flagged(
                hdu['SPECINDEX_MASK'].data[specindex['D4000'], :, :],
                'DONOTUSE'))
        ud4000 = numpy.ma.MaskedArray(
            hdu['SPECINDEX'].data.copy()[specindex['D4000'], :, :],
            mask=numpy.invert(
                bm.flagged(
                    hdu['SPECINDEX_MASK'].data[specindex['D4000'], :, :],
                    'UNRELIABLE')))
        ud4000[numpy.invert(numpy.ma.getmaskarray(ud4000))] = 0.0
        dn4000 = numpy.ma.MaskedArray(
            hdu['SPECINDEX'].data.copy()[specindex['Dn4000'], :, :],
            mask=bm.flagged(
                hdu['SPECINDEX_MASK'].data[specindex['Dn4000'], :, :],
                'DONOTUSE'))
        udn4000 = numpy.ma.MaskedArray(
            hdu['SPECINDEX'].data.copy()[specindex['Dn4000'], :, :],
            mask=numpy.invert(
                bm.flagged(
                    hdu['SPECINDEX_MASK'].data[specindex['Dn4000'], :, :],
                    'UNRELIABLE')))
        udn4000[numpy.invert(numpy.ma.getmaskarray(udn4000))] = 0.0
    else:
        output_shape = spxflx.shape
        d4000 = numpy.ma.masked_all(output_shape)
        ud4000 = numpy.ma.masked_all(output_shape)
        dn4000 = numpy.ma.masked_all(output_shape)
        udn4000 = numpy.ma.masked_all(output_shape)

    # Get the limits to apply
    flux_lim = numpy.power(10,
                           growth_lim(numpy.ma.log10(spxflx), 0.90, fac=1.05))
    t = numpy.ma.append(numpy.ma.log10(spxsnr), numpy.ma.log10(binsnr))
    snr_lim = numpy.power(10, growth_lim(t, 0.90, fac=1.05))
    bin_lim = [numpy.ma.amin(binid), numpy.ma.amax(binid)]

    res_lim = numpy.power(10, growth_lim(numpy.ma.log10(scfres),
                                         0.90,
                                         fac=1.05))
    chi_lim = growth_lim(scrchi, 0.90, fac=1.05)
    t = numpy.ma.append(strvel, hagvel)
    vel_lim = growth_lim(t, 0.85, fac=1.10, midpoint=0.0)
    if vel_lim[0] < -350:
        vel_lim[0] = -350
    if vel_lim[1] > 350:
        vel_lim[1] = 350
    t = numpy.ma.append(numpy.ma.log10(strsig), numpy.ma.log10(hagsig))
    sig_lim = numpy.power(10, growth_lim(t, 0.90, fac=1.05))

    t = numpy.ma.append(
        numpy.ma.append(numpy.ma.log10(hasflx), numpy.ma.log10(hagflx)),
        numpy.ma.append(numpy.ma.log10(hbsflx), numpy.ma.log10(hbgflx)))
    #    t = numpy.ma.log10(t)
    hflx_lim = numpy.power(10, growth_lim(t, 0.95, fac=1.10))
    #    hflx_lim = [ -0.3, 2.2 ]
    t = numpy.ma.append(d4000, dn4000)
    #    d4000_lim = growth_lim(t, 0.90, 1.05)
    d4000_lim = [1.0, 2.5]

    font = {'size': 6}
    rc('font', **font)

    w, h = pyplot.figaspect(1)
    fig = pyplot.figure(figsize=(1.5 * w, 1.5 * h))

    dx = 0.22
    left = 0.05
    top = 0.94
    dw = 0.005

    snr_levels = [0.5, 1.0, 1.5, 2.0]

    ax = init_ax(fig, [left, top - dx, dx, dx])
    ax.xaxis.set_major_formatter(ticker.NullFormatter())
    cax = fig.add_axes([left + dx * 0.65, top - 0.07 * dx, 0.27 * dx, 0.01])
    cbticks = [flux_lim[0] * 1.1, flux_lim[1] / 1.1]
    masked_imshow(fig,
                  ax,
                  cax,
                  spxflx,
                  extent=extent,
                  norm=colors.LogNorm(vmin=flux_lim[0], vmax=flux_lim[1]),
                  cmap='YlGnBu_r',
                  zorder=4,
                  orientation='horizontal',
                  contour_data=numpy.ma.log10(spxsnr),
                  levels=snr_levels,
                  cbticks=cbticks,
                  cbformat=ticker.ScalarFormatter())
    ax.add_patch(
        map_beam_patch(extent, ax, facecolor='0.7', edgecolor='k', zorder=4))
    ax.text(0.99,
            0.05,
            r'g-band S (spx)',
            horizontalalignment='right',
            verticalalignment='center',
            transform=ax.transAxes)

    ax = init_ax(fig, [left + dx + dw, top - dx, dx, dx])
    ax.xaxis.set_major_formatter(ticker.NullFormatter())
    ax.yaxis.set_major_formatter(ticker.NullFormatter())
    cax = fig.add_axes(
        [left + dx + dw + dx * 0.65, top - 0.07 * dx, 0.27 * dx, 0.01])
    cbticks = [snr_lim[0] * 1.1, snr_lim[1] / 1.1]
    masked_imshow(fig,
                  ax,
                  cax,
                  spxsnr,
                  extent=extent,
                  norm=colors.LogNorm(vmin=snr_lim[0], vmax=snr_lim[1]),
                  cmap='YlGnBu_r',
                  zorder=4,
                  orientation='horizontal',
                  contour_data=numpy.ma.log10(spxsnr),
                  levels=snr_levels,
                  cbticks=cbticks,
                  cbformat=ticker.ScalarFormatter())  #'%.0f')
    ax.add_patch(
        map_beam_patch(extent, ax, facecolor='0.7', edgecolor='k', zorder=4))
    ax.text(0.99,
            0.05,
            r'g-band S/N (spx)',
            horizontalalignment='right',
            verticalalignment='center',
            transform=ax.transAxes)

    ax.text(1.0,
            1.1,
            r'{0}-{1}; {2}'.format(plate, ifudesign,
                                   hdu['PRIMARY'].header['MANGAID']),
            horizontalalignment='center',
            verticalalignment='center',
            transform=ax.transAxes,
            fontsize=20)

    ax = init_ax(fig, [left + 2 * dx + 2 * dw, top - dx, dx, dx])
    ax.xaxis.set_major_formatter(ticker.NullFormatter())
    ax.yaxis.set_major_formatter(ticker.NullFormatter())
    cax = fig.add_axes(
        [left + 2 * dx + 2 * dw + dx * 0.65, top - 0.07 * dx, 0.27 * dx, 0.01])
    masked_imshow(fig,
                  ax,
                  cax,
                  binid[0, :, :],
                  extent=extent,
                  vmin=bin_lim[0],
                  vmax=bin_lim[1],
                  cmap='CMRmap',
                  zorder=4,
                  orientation='horizontal',
                  contour_data=numpy.ma.log10(spxsnr),
                  levels=snr_levels,
                  cbformat=ticker.ScalarFormatter(),
                  cbticks=bin_lim)
    ax.add_patch(
        map_beam_patch(extent, ax, facecolor='0.7', edgecolor='k', zorder=4))
    ax.text(0.99,
            0.05,
            r'bin ID',
            horizontalalignment='right',
            verticalalignment='center',
            transform=ax.transAxes)

    ax = init_ax(fig, [left + 3 * dx + 3 * dw, top - dx, dx, dx])
    ax.xaxis.set_major_formatter(ticker.NullFormatter())
    ax.yaxis.set_major_formatter(ticker.NullFormatter())
    cax = fig.add_axes(
        [left + 3 * dx + 3 * dw + dx * 0.65, top - 0.07 * dx, 0.27 * dx, 0.01])
    cbticks = [snr_lim[0] * 1.1, snr_lim[1] / 1.1]
    masked_imshow(fig,
                  ax,
                  cax,
                  binsnr,
                  extent=extent,
                  norm=colors.LogNorm(vmin=snr_lim[0], vmax=snr_lim[1]),
                  cmap='YlGnBu_r',
                  zorder=4,
                  orientation='horizontal',
                  contour_data=numpy.ma.log10(spxsnr),
                  levels=snr_levels,
                  cbticks=cbticks,
                  cbformat=ticker.ScalarFormatter())  #'%.0f')
    ax.add_patch(
        map_beam_patch(extent, ax, facecolor='0.7', edgecolor='k', zorder=4))
    ax.text(0.99,
            0.05,
            r'g-band S/N (bin)',
            horizontalalignment='right',
            verticalalignment='center',
            transform=ax.transAxes)

    ax = init_ax(fig, [left, top - 2 * dx - dw, dx, dx])
    ax.xaxis.set_major_formatter(ticker.NullFormatter())
    cax = fig.add_axes(
        [left + dx * 0.65, top - dx - dw - 0.07 * dx, 0.27 * dx, 0.01])
    cbticks = [res_lim[0] * 1.1, res_lim[1] / 1.1]
    masked_imshow(fig,
                  ax,
                  cax,
                  scfres,
                  extent=extent,
                  norm=colors.LogNorm(vmin=res_lim[0], vmax=res_lim[1]),
                  cmap='inferno',
                  zorder=4,
                  orientation='horizontal',
                  contour_data=numpy.ma.log10(spxsnr),
                  levels=snr_levels,
                  cbticks=cbticks,
                  cbformat=ticker.ScalarFormatter())  #'%.0f')
    ax.add_patch(
        map_beam_patch(extent, ax, facecolor='0.7', edgecolor='k', zorder=4))
    ax.text(0.99,
            0.05,
            r'pPXF Frac. Resid.',
            horizontalalignment='right',
            verticalalignment='center',
            transform=ax.transAxes)

    ax = init_ax(fig, [left + dx + dw, top - 2 * dx - dw, dx, dx])
    ax.xaxis.set_major_formatter(ticker.NullFormatter())
    ax.yaxis.set_major_formatter(ticker.NullFormatter())
    cax = fig.add_axes([
        left + dx + dw + dx * 0.65, top - dx - dw - 0.07 * dx, 0.27 * dx, 0.01
    ])
    cbticks = [
        numpy.round(chi_lim[0] + 0.01, decimals=2),
        numpy.round(chi_lim[1] - 0.01, decimals=2)
    ]
    masked_imshow(fig,
                  ax,
                  cax,
                  scrchi,
                  extent=extent,
                  vmin=chi_lim[0],
                  vmax=chi_lim[1],
                  cmap='inferno',
                  zorder=4,
                  orientation='horizontal',
                  contour_data=numpy.ma.log10(spxsnr),
                  levels=snr_levels,
                  cbticks=cbticks,
                  cbformat=ticker.ScalarFormatter())  #'%.0f')
    ax.add_patch(
        map_beam_patch(extent, ax, facecolor='0.7', edgecolor='k', zorder=4))
    ax.text(0.99,
            0.05,
            r'${\rm pPXF}\ \chi^2_\nu$',
            horizontalalignment='right',
            verticalalignment='center',
            transform=ax.transAxes)

    ax = init_ax(fig, [left + 2 * dx + 2 * dw, top - 2 * dx - dw, dx, dx])
    ax.xaxis.set_major_formatter(ticker.NullFormatter())
    ax.yaxis.set_major_formatter(ticker.NullFormatter())
    cax = fig.add_axes([
        left + 2 * dx + 2 * dw + dx * 0.65, top - dx - dw - 0.07 * dx,
        0.27 * dx, 0.01
    ])
    cbticks = [vel_lim[0] / 1.1, 0.0, vel_lim[1] / 1.1]
    masked_imshow(fig,
                  ax,
                  cax,
                  strvel,
                  extent=extent,
                  vmin=vel_lim[0],
                  vmax=vel_lim[1],
                  cmap='RdBu_r',
                  zorder=4,
                  orientation='horizontal',
                  contour_data=numpy.ma.log10(spxsnr),
                  levels=snr_levels,
                  cbticks=cbticks,
                  cbformat=ticker.ScalarFormatter())  #'%.0f')
    #    im = ax.imshow(strvel, origin='lower', interpolation='nearest', cmap='RdBu_r',
    #                   zorder=4, extent=extent, vmin=vel_lim[0], vmax=vel_lim[1])
    #    im2 = ax.imshow(ustrvel, origin='lower', interpolation='nearest', cmap='Greens_r',
    #                    vmin=0, vmax=1, zorder=5, alpha=0.3, extent=extent)
    #    cnt = ax.contour(numpy.ma.log10(spxsnr), origin='lower', extent=im.get_extent(),
    #                     colors='0.5', levels=snr_levels, linewidths=1.5, zorder=6)
    #    pyplot.colorbar(im, cax=cax, orientation='horizontal',
    #                    ticks=[numpy.round(vel_lim[0]+1), numpy.round(vel_lim[1]-1)], format='%.0f')
    ax.add_patch(
        map_beam_patch(extent, ax, facecolor='0.7', edgecolor='k', zorder=4))
    ax.text(0.99,
            0.05,
            r'$V_\ast$',
            horizontalalignment='right',
            verticalalignment='center',
            transform=ax.transAxes)

    ax = init_ax(fig, [left + 3 * dx + 3 * dw, top - 2 * dx - dw, dx, dx])
    ax.xaxis.set_major_formatter(ticker.NullFormatter())
    ax.yaxis.set_major_formatter(ticker.NullFormatter())
    cax = fig.add_axes([
        left + 3 * dx + 3 * dw + dx * 0.65, top - dx - dw - 0.07 * dx,
        0.27 * dx, 0.01
    ])
    cbticks = [
        sig_lim[0] * 1.1,
        numpy.power(10, numpy.mean(numpy.log10(sig_lim))), sig_lim[1] / 1.1
    ]
    masked_imshow(fig,
                  ax,
                  cax,
                  strsig,
                  extent=extent,
                  norm=colors.LogNorm(vmin=sig_lim[0], vmax=sig_lim[1]),
                  cmap='viridis',
                  zorder=4,
                  orientation='horizontal',
                  contour_data=numpy.ma.log10(spxsnr),
                  levels=snr_levels,
                  cbticks=cbticks,
                  cbformat=ticker.ScalarFormatter())  #'%.0f')
    #    im = ax.imshow(numpy.ma.log10(strsig), origin='lower', interpolation='nearest',
    #                   cmap='viridis', zorder=4, extent=extent, vmin=sig_lim[0], vmax=sig_lim[1])
    #    im2 = ax.imshow(ustrsig, origin='lower', interpolation='nearest', cmap='Reds_r',
    #                    vmin=0, vmax=1, zorder=5, alpha=0.3, extent=extent)
    #    cnt = ax.contour(numpy.ma.log10(spxsnr), origin='lower', extent=im.get_extent(),
    #                     colors='0.5', levels=snr_levels, linewidths=1.5, zorder=6)
    #    pyplot.colorbar(im, cax=cax, orientation='horizontal',
    #                    ticks=[numpy.round(sig_lim[0]+0.1, decimals=1),
    #                           numpy.round(sig_lim[1]-0.1, decimals=1)], format='%.1f')
    ax.add_patch(
        map_beam_patch(extent, ax, facecolor='0.7', edgecolor='k', zorder=4))
    ax.text(0.99,
            0.05,
            r'$\sigma_\ast$',
            horizontalalignment='right',
            verticalalignment='center',
            transform=ax.transAxes)

    ax = init_ax(fig, [left, top - 3 * dx - 2 * dw, dx, dx])
    ax.xaxis.set_major_formatter(ticker.NullFormatter())
    cax = fig.add_axes(
        [left + dx * 0.65, top - 2 * dx - 2 * dw - 0.07 * dx, 0.27 * dx, 0.01])
    cbticks = [hflx_lim[0] * 1.1, hflx_lim[1] / 1.1]
    masked_imshow(fig,
                  ax,
                  cax,
                  hasflx,
                  extent=extent,
                  norm=colors.LogNorm(vmin=hflx_lim[0], vmax=hflx_lim[1]),
                  cmap='inferno',
                  zorder=4,
                  orientation='horizontal',
                  contour_data=numpy.ma.log10(spxsnr),
                  levels=snr_levels,
                  cbticks=cbticks,
                  cbformat=ticker.ScalarFormatter())  #'%.0f')
    #    im = ax.imshow(hasflx, origin='lower', interpolation='nearest', cmap='inferno',
    #                   zorder=4, extent=extent, vmin=hflx_lim[0], vmax=hflx_lim[1])
    #    im2 = ax.imshow(uhasflx, origin='lower', interpolation='nearest', cmap='Greens_r',
    #              vmin=0, vmax=1, zorder=5, alpha=0.3, extent=extent)
    #    cnt = ax.contour(numpy.ma.log10(spxsnr), origin='lower', extent=im.get_extent(),
    #                     colors='0.5', levels=snr_levels, linewidths=1.5, zorder=6)
    #    pyplot.colorbar(im, cax=cax, orientation='horizontal',
    #                    ticks=[numpy.round(hflx_lim[0]+0.1, decimals=1),
    #                           numpy.round(hflx_lim[1]-0.1, decimals=1)], format='%.1f')
    ax.add_patch(
        map_beam_patch(extent, ax, facecolor='0.7', edgecolor='k', zorder=4))
    ax.text(0.99,
            0.05,
            r'${\rm H}\alpha\ {\rm flux}$ (sum)',
            horizontalalignment='right',
            verticalalignment='center',
            transform=ax.transAxes)

    ax = init_ax(fig, [left + dx + dw, top - 3 * dx - 2 * dw, dx, dx])
    ax.xaxis.set_major_formatter(ticker.NullFormatter())
    ax.yaxis.set_major_formatter(ticker.NullFormatter())
    cax = fig.add_axes([
        left + dx + dw + dx * 0.65, top - 2 * dx - 2 * dw - 0.07 * dx,
        0.27 * dx, 0.01
    ])
    cbticks = [hflx_lim[0] * 1.1, hflx_lim[1] / 1.1]
    masked_imshow(fig,
                  ax,
                  cax,
                  hagflx,
                  extent=extent,
                  norm=colors.LogNorm(vmin=hflx_lim[0], vmax=hflx_lim[1]),
                  cmap='inferno',
                  zorder=4,
                  orientation='horizontal',
                  contour_data=numpy.ma.log10(spxsnr),
                  levels=snr_levels,
                  cbticks=cbticks,
                  cbformat=ticker.ScalarFormatter())  #'%.0f')
    #    im = ax.imshow(hagflx, origin='lower', interpolation='nearest', cmap='inferno',
    #                   zorder=4, extent=extent, vmin=hflx_lim[0], vmax=hflx_lim[1])
    #    im2 = ax.imshow(uhagflx, origin='lower', interpolation='nearest', cmap='Greens_r',
    #              vmin=0, vmax=1, zorder=5, alpha=0.3, extent=extent)
    #    cnt = ax.contour(numpy.ma.log10(spxsnr), origin='lower', extent=im.get_extent(),
    #                     colors='0.5', levels=snr_levels, linewidths=1.5, zorder=6)
    #    pyplot.colorbar(im, cax=cax, orientation='horizontal',
    #                    ticks=[numpy.round(hflx_lim[0]+0.1, decimals=1),
    #                           numpy.round(hflx_lim[1]-0.1, decimals=1)], format='%.1f')
    ax.add_patch(
        map_beam_patch(extent, ax, facecolor='0.7', edgecolor='k', zorder=4))
    ax.text(0.99,
            0.05,
            r'${\rm H}\alpha\ {\rm flux}$ (Gauss)',
            horizontalalignment='right',
            verticalalignment='center',
            transform=ax.transAxes)

    ax = init_ax(fig, [left + 2 * dx + 2 * dw, top - 3 * dx - 2 * dw, dx, dx])
    ax.xaxis.set_major_formatter(ticker.NullFormatter())
    ax.yaxis.set_major_formatter(ticker.NullFormatter())
    cax = fig.add_axes([
        left + 2 * dx + 2 * dw + dx * 0.65, top - 2 * dx - 2 * dw - 0.07 * dx,
        0.27 * dx, 0.01
    ])
    cbticks = [vel_lim[0] / 1.1, 0.0, vel_lim[1] / 1.1]
    masked_imshow(fig,
                  ax,
                  cax,
                  hagvel,
                  extent=extent,
                  vmin=vel_lim[0],
                  vmax=vel_lim[1],
                  cmap='RdBu_r',
                  zorder=4,
                  orientation='horizontal',
                  contour_data=numpy.ma.log10(spxsnr),
                  levels=snr_levels,
                  cbticks=cbticks,
                  cbformat=ticker.ScalarFormatter())  #'%.0f')
    #    im = ax.imshow(hagvel, origin='lower', interpolation='nearest', cmap='RdBu_r',
    #                   zorder=4, extent=extent, vmin=vel_lim[0], vmax=vel_lim[1])
    #    im2 = ax.imshow(uhagvel, origin='lower', interpolation='nearest', cmap='Greens_r',
    #              vmin=0, vmax=1, zorder=5, alpha=0.3, extent=extent)
    #    cnt = ax.contour(numpy.ma.log10(spxsnr), origin='lower', extent=im.get_extent(),
    #                     colors='0.5', levels=snr_levels, linewidths=1.5, zorder=6)
    #    pyplot.colorbar(im, cax=cax, orientation='horizontal',
    #                    ticks=[numpy.round(vel_lim[0]+1), numpy.round(vel_lim[1]-1)], format='%.0f')
    ax.add_patch(
        map_beam_patch(extent, ax, facecolor='0.7', edgecolor='k', zorder=4))
    ax.text(0.99,
            0.05,
            r'$V_{{\rm H}\alpha}$',
            horizontalalignment='right',
            verticalalignment='center',
            transform=ax.transAxes)

    ax = init_ax(fig, [left + 3 * dx + 3 * dw, top - 3 * dx - 2 * dw, dx, dx])
    ax.xaxis.set_major_formatter(ticker.NullFormatter())
    ax.yaxis.set_major_formatter(ticker.NullFormatter())
    cax = fig.add_axes([
        left + 3 * dx + 3 * dw + dx * 0.65, top - 2 * dx - 2 * dw - 0.07 * dx,
        0.27 * dx, 0.01
    ])
    cbticks = [
        sig_lim[0] * 1.1,
        numpy.power(10, numpy.mean(numpy.log10(sig_lim))), sig_lim[1] / 1.1
    ]
    masked_imshow(fig,
                  ax,
                  cax,
                  hagsig,
                  extent=extent,
                  norm=colors.LogNorm(vmin=sig_lim[0], vmax=sig_lim[1]),
                  cmap='viridis',
                  zorder=4,
                  orientation='horizontal',
                  contour_data=numpy.ma.log10(spxsnr),
                  levels=snr_levels,
                  cbticks=cbticks,
                  cbformat=ticker.ScalarFormatter())  #'%.0f')
    #    im = ax.imshow(numpy.ma.log10(hagsig), origin='lower', interpolation='nearest',
    #                   cmap='viridis', zorder=4, extent=extent, vmin=sig_lim[0], vmax=sig_lim[1])
    #    im2 = ax.imshow(uhagsig, origin='lower', interpolation='nearest', cmap='Reds_r',
    #                    vmin=0, vmax=1, zorder=5, alpha=0.3, extent=extent)
    #    cnt = ax.contour(numpy.ma.log10(spxsnr), origin='lower', extent=im.get_extent(),
    #                     colors='0.5', levels=snr_levels, linewidths=1.5, zorder=6)
    #    pyplot.colorbar(im, cax=cax, orientation='horizontal',
    #                    ticks=[numpy.round(sig_lim[0]+0.1, decimals=1),
    #                           numpy.round(sig_lim[1]-0.1, decimals=1)], format='%.1f')
    ax.add_patch(
        map_beam_patch(extent, ax, facecolor='0.7', edgecolor='k', zorder=4))
    ax.text(0.99,
            0.05,
            r'$\sigma_{{\rm H}\alpha}$',
            horizontalalignment='right',
            verticalalignment='center',
            transform=ax.transAxes)

    ax = init_ax(fig, [left, top - 4 * dx - 3 * dw, dx, dx])
    cax = fig.add_axes(
        [left + dx * 0.65, top - 3 * dx - 3 * dw - 0.07 * dx, 0.27 * dx, 0.01])
    cbticks = [hflx_lim[0] * 1.1, hflx_lim[1] / 1.1]
    masked_imshow(fig,
                  ax,
                  cax,
                  hbsflx,
                  extent=extent,
                  norm=colors.LogNorm(vmin=hflx_lim[0], vmax=hflx_lim[1]),
                  cmap='inferno',
                  zorder=4,
                  orientation='horizontal',
                  contour_data=numpy.ma.log10(spxsnr),
                  levels=snr_levels,
                  cbticks=cbticks,
                  cbformat=ticker.ScalarFormatter())  #'%.0f')
    #    im = ax.imshow(hbsflx, origin='lower', interpolation='nearest', cmap='inferno',
    #                   zorder=4, extent=extent, vmin=hflx_lim[0], vmax=hflx_lim[1])
    #    im2 = ax.imshow(uhbsflx, origin='lower', interpolation='nearest', cmap='Greens_r',
    #              vmin=0, vmax=1, zorder=5, alpha=0.3, extent=extent)
    #    cnt = ax.contour(numpy.ma.log10(spxsnr), origin='lower', extent=im.get_extent(),
    #                     colors='0.5', levels=snr_levels, linewidths=1.5, zorder=6)
    #    pyplot.colorbar(im, cax=cax, orientation='horizontal',
    #                    ticks=[numpy.round(hflx_lim[0]+0.1, decimals=1),
    #                           numpy.round(hflx_lim[1]-0.1, decimals=1)], format='%.1f')
    ax.add_patch(
        map_beam_patch(extent, ax, facecolor='0.7', edgecolor='k', zorder=4))
    ax.text(0.99,
            0.05,
            r'${\rm H}\beta\ {\rm flux}$ (sum)',
            horizontalalignment='right',
            verticalalignment='center',
            transform=ax.transAxes)

    ax = init_ax(fig, [left + dx + dw, top - 4 * dx - 3 * dw, dx, dx])
    ax.yaxis.set_major_formatter(ticker.NullFormatter())
    cax = fig.add_axes([
        left + dx + dw + dx * 0.65, top - 3 * dx - 3 * dw - 0.07 * dx,
        0.27 * dx, 0.01
    ])
    cbticks = [hflx_lim[0] * 1.1, hflx_lim[1] / 1.1]
    masked_imshow(fig,
                  ax,
                  cax,
                  hbgflx,
                  extent=extent,
                  norm=colors.LogNorm(vmin=hflx_lim[0], vmax=hflx_lim[1]),
                  cmap='inferno',
                  zorder=4,
                  orientation='horizontal',
                  contour_data=numpy.ma.log10(spxsnr),
                  levels=snr_levels,
                  cbticks=cbticks,
                  cbformat=ticker.ScalarFormatter())  #'%.0f')
    #    im = ax.imshow(hbgflx, origin='lower', interpolation='nearest', cmap='inferno',
    #                   zorder=4, extent=extent, vmin=hflx_lim[0], vmax=hflx_lim[1])
    #    im2 = ax.imshow(uhbgflx, origin='lower', interpolation='nearest', cmap='Greens_r',
    #              vmin=0, vmax=1, zorder=5, alpha=0.3, extent=extent)
    #    cnt = ax.contour(numpy.ma.log10(spxsnr), origin='lower', extent=im.get_extent(),
    #                     colors='0.5', levels=snr_levels, linewidths=1.5, zorder=6)
    #    pyplot.colorbar(im, cax=cax, orientation='horizontal',
    #                    ticks=[numpy.round(hflx_lim[0]+0.1, decimals=1),
    #                           numpy.round(hflx_lim[1]-0.1, decimals=1)], format='%.1f')
    ax.add_patch(
        map_beam_patch(extent, ax, facecolor='0.7', edgecolor='k', zorder=4))
    ax.text(0.99,
            0.05,
            r'${\rm H}\beta\ {\rm flux}$ (Gauss)',
            horizontalalignment='right',
            verticalalignment='center',
            transform=ax.transAxes)

    ax = init_ax(fig, [left + 2 * dx + 2 * dw, top - 4 * dx - 3 * dw, dx, dx])
    ax.yaxis.set_major_formatter(ticker.NullFormatter())
    cax = fig.add_axes([
        left + 2 * dx + 2 * dw + dx * 0.65, top - 3 * dx - 3 * dw - 0.07 * dx,
        0.27 * dx, 0.01
    ])
    masked_imshow(fig,
                  ax,
                  cax,
                  d4000,
                  extent=extent,
                  vmin=d4000_lim[0],
                  vmax=d4000_lim[1],
                  cmap='RdBu_r',
                  zorder=4,
                  orientation='horizontal',
                  contour_data=numpy.ma.log10(spxsnr),
                  levels=snr_levels,
                  cbticks=d4000_lim,
                  cbformat=ticker.ScalarFormatter())
    #    im = ax.imshow(d4000, origin='lower', interpolation='nearest', cmap='RdBu_r',
    #                   zorder=4, extent=extent, vmin=d4000_lim[0], vmax=d4000_lim[1])
    #    im2 = ax.imshow(ud4000, origin='lower', interpolation='nearest', cmap='Greens_r',
    #                    vmin=0, vmax=1, zorder=5, alpha=0.3, extent=extent)
    #    cnt = ax.contour(numpy.ma.log10(spxsnr), origin='lower', extent=im.get_extent(),
    #                     colors='0.5', levels=snr_levels, linewidths=1.5, zorder=6)
    #    pyplot.colorbar(im, cax=cax, orientation='horizontal', ticks=d4000_lim, format='%.1f')
    ax.add_patch(
        map_beam_patch(extent, ax, facecolor='0.7', edgecolor='k', zorder=4))
    ax.text(0.99,
            0.05,
            r'D4000',
            horizontalalignment='right',
            verticalalignment='center',
            transform=ax.transAxes)

    ax = init_ax(fig, [left + 3 * dx + 3 * dw, top - 4 * dx - 3 * dw, dx, dx])
    ax.yaxis.set_major_formatter(ticker.NullFormatter())
    cax = fig.add_axes([
        left + 3 * dx + 3 * dw + dx * 0.65, top - 3 * dx - 3 * dw - 0.07 * dx,
        0.27 * dx, 0.01
    ])
    masked_imshow(fig,
                  ax,
                  cax,
                  dn4000,
                  extent=extent,
                  vmin=d4000_lim[0],
                  vmax=d4000_lim[1],
                  cmap='RdBu_r',
                  zorder=4,
                  orientation='horizontal',
                  contour_data=numpy.ma.log10(spxsnr),
                  levels=snr_levels,
                  cbticks=d4000_lim,
                  cbformat=ticker.ScalarFormatter())
    #    im = ax.imshow(dn4000, origin='lower', interpolation='nearest', cmap='RdBu_r',
    #                   zorder=4, extent=extent, vmin=d4000_lim[0], vmax=d4000_lim[1])
    #    im2 = ax.imshow(udn4000, origin='lower', interpolation='nearest', cmap='Greens_r',
    #                    vmin=0, vmax=1, zorder=5, alpha=0.3, extent=extent)
    #    cnt = ax.contour(numpy.ma.log10(spxsnr), origin='lower', extent=im.get_extent(),
    #                     colors='0.5', levels=snr_levels, linewidths=1.5, zorder=6)
    #    pyplot.colorbar(im, cax=cax, orientation='horizontal', ticks=d4000_lim, format='%.1f')
    ax.add_patch(
        map_beam_patch(extent, ax, facecolor='0.7', edgecolor='k', zorder=4))
    ax.text(0.99,
            0.05,
            r'Dn4000',
            horizontalalignment='right',
            verticalalignment='center',
            transform=ax.transAxes)

    if ofile is not None:
        fig.canvas.print_figure(ofile, bbox_inches='tight')
        print('Writing: {0}'.format(ofile))
    else:
        pyplot.show()

    fig.clear()
    pyplot.close(fig)