예제 #1
0
def plt_eovsa_image(eofiles, figoutdir='./'):
    import matplotlib.pyplot as plt
    import matplotlib.colors as colors
    from astropy.visualization.stretch import AsinhStretch, LinearStretch, SqrtStretch
    from astropy.visualization import ImageNormalize
    from suncasa.utils import plot_mapX as pmX
    from sunpy import map as smap
    import astropy.units as u
    from mpl_toolkits.axes_grid1 import make_axes_locatable
    import matplotlib.colorbar as colorbar

    # It is expected that nfiles will be either 4 (for older 34-band data) or 6 (for newer 52-band data)
    nfiles = len(eofiles)
    plt.ioff()
    fig = plt.figure(figsize=(5 * nfiles // 2, 9))

    axs = []
    cmap = 'gist_heat'
    for idx, eofile in enumerate(eofiles):
        ax = fig.add_subplot(2, nfiles // 2, idx + 1)
        axs.append(ax)
        # ax = axs[idx]
        eomap = smap.Map(eofile)
        tb_disk = eomap.meta['TBDISK']
        vmaxs = [70.0e4, 30e4, 18e4, 13e4, 8e4, 6e4]
        vmins = [-18.0e3, -8e3, -4.8e3, -3.4e3, -2.1e3, -1.6e3]
        # norm = colors.Normalize(vmin=vmins[idx], vmax=vmaxs[idx])
        stretch = AsinhStretch(a=0.15)
        norm = ImageNormalize(vmin=vmins[idx], vmax=vmaxs[idx], stretch=stretch)

        # norm = colors.Normalize(vmin=tb_disk * (-0.2), vmax=0.5*np.nanmax(eomap.data))
        eomap_ = pmX.Sunmap(eomap)
        eomap_.imshow(axes=ax, cmap=cmap, norm=norm)
        eomap_.draw_limb(axes=ax, lw=0.5, alpha=0.5)
        eomap_.draw_grid(axes=ax, grid_spacing=10. * u.deg, lw=0.5)
        divider = make_axes_locatable(ax)
        cax = divider.append_axes('right', size='2.0%', pad=0.08)
        cax.tick_params(direction='in')
        clb = colorbar.ColorbarBase(cax, cmap=cmap, norm=norm)
        clb.set_label(r'T$_b$ [$\times$10$^3$K]')
        if idx != nfiles / 2:
            ax.set_xlabel('')
            ax.set_ylabel('')
            ax.set_xticklabels([])
            ax.set_yticklabels([])
        ax.tick_params(direction="out")
        ax.text(0.02, 0.98,
                'EOVSA {:.1f} GHz   {}'.format(eomap.meta['CRVAL3'] / 1e9, eomap.date.strftime('%d-%b-%Y 20:00 UT')),
                transform=ax.transAxes, color='w', ha='left', va='top', fontsize=8, fontweight='bold')
        ax.text(0.02, 0.02, 'Max Tb {:.0f} K'.format(np.nanmax(eomap.data)),
                transform=ax.transAxes, color='w', ha='left', va='bottom', fontsize=8, fontweight='bold')
        ax.set_xlim(-1200, 1200)
        ax.set_ylim(-1200, 1200)
    fig.tight_layout()
    figname = os.path.join(figoutdir, 'eovsa_qlimg_{}.png'.format(eomap.date.strftime('%Y%m%d')))
    fig.savefig(figname, dpi=150)
    plt.close(fig)
    plt.ion()
    return figname
def pltEovsaQlookImage(timobj, spws, vmaxs, vmins, dpis_dict, fig=None, ax=None, overwrite=False, verbose=False):
    plt.ioff()
    dateobj = timobj.to_datetime()
    datestrdir = dateobj.strftime("%Y/%m/%d/")
    imgindir = imgfitsdir + datestrdir

    # if not os.path.exists(imgindir):
    #     os.makedirs(imgindir)
    cmap = cm_smap.get_cmap('sdoaia304')

    if fig is None or ax is None:
        mkfig = True
    else:
        mkfig = False

    if mkfig:
        fig, ax = plt.subplots(figsize=(8, 8))
        fig.subplots_adjust(bottom=0.0, top=1.0, left=0.0, right=1.0)

    if verbose: print('Processing EOVSA images for date {}'.format(dateobj.strftime('%Y-%m-%d')))
    for s, sp in enumerate(spws):
        fexists = []
        for l, dpi in dpis_dict.items():
            figname = os.path.join(movieoutdir, '{}_eovsa_bd{:02d}.jpg'.format(l, s + 1))
            fexists.append(os.path.exists(figname))

        if overwrite or (False in fexists):
            ax.cla()
            spwstr = '-'.join(['{:02d}'.format(int(sp_)) for sp_ in sp.split('~')])
            eofile = imgindir + 'eovsa_{}.spw{}.tb.disk.fits'.format(dateobj.strftime('%Y%m%d'), spwstr)
            if not os.path.exists(eofile): continue
            if not os.path.exists(movieoutdir): os.makedirs(movieoutdir)
            eomap = smap.Map(eofile)
            norm = colors.Normalize(vmin=vmins[s], vmax=vmaxs[s])
            eomap_ = pmX.Sunmap(eomap)
            eomap_.imshow(axes=ax, cmap=cmap, norm=norm)
            eomap_.draw_limb(axes=ax, lw=0.5, alpha=0.5)
            eomap_.draw_grid(axes=ax, grid_spacing=10. * u.deg, lw=0.5)
            ax.set_xlabel('')
            ax.set_ylabel('')
            ax.set_xticklabels([])
            ax.set_yticklabels([])
            ax.text(0.02, 0.02,
                    'EOVSA {:.1f} GHz  {}'.format(eomap.meta['CRVAL3'] / 1e9, eomap.date.strftime('%d-%b-%Y 20:00 UT')),
                    transform=ax.transAxes, color='w', ha='left', va='bottom', fontsize=9)
            ax.text(0.98, 0.02, 'Max Tb {:.0f} K'.format(np.nanmax(eomap.data)),
                    transform=ax.transAxes, color='w', ha='right', va='bottom', fontsize=9)
            ax.set_xlim(-1227, 1227)
            ax.set_ylim(-1227, 1227)

            for l, dpi in dpis_dict.items():
                figname = os.path.join(movieoutdir, '{}_eovsa_bd{:02d}.jpg'.format(l, s + 1))
                fig.savefig(figname, dpi=np.int(dpi), quality=85)
    if mkfig:
        pass
    else:
        plt.close(fig)
    return
예제 #3
0
def pltEmptyImage(datestr, spws, vmaxs, vmins, dpis_dict={'t': 32.0}):
    plt.ioff()
    dateobj = datetime.strptime(datestr, "%Y-%m-%d")
    datastrdir = dateobj.strftime("%Y/%m/%d/")
    imgindir = imgfitsdir + datastrdir
    imgoutdir = './nodata/'

    cmap = cm.get_cmap('sdoaia304')

    fig, ax = plt.subplots(figsize=(8, 8))
    fig.subplots_adjust(bottom=0.0, top=1.0, left=0.0, right=1.0)

    rect = patches.Rectangle((-1227, -300),
                             1227 * 2,
                             300 * 2,
                             linewidth=0,
                             edgecolor='none',
                             facecolor='k',
                             alpha=0.5)

    for s, sp in enumerate(spws):
        ax.cla()
        spwstr = '-'.join(['{:02d}'.format(int(sp_)) for sp_ in sp.split('~')])
        eofile = imgindir + 'eovsa_{}.spw{}.tb.disk.fits'.format(
            dateobj.strftime('%Y%m%d'), spwstr)
        if not os.path.exists(eofile): continue
        if not os.path.exists(imgoutdir): os.makedirs(imgoutdir)
        eomap = smap.Map(eofile)
        norm = colors.Normalize(vmin=vmins[s], vmax=vmaxs[s])
        eomap_ = pmX.Sunmap(eomap)
        eomap_.imshow(axes=ax, cmap=cmap, norm=norm, alpha=0.75)
        eomap_.draw_limb(axes=ax, lw=0.5, alpha=0.5)
        eomap_.draw_grid(axes=ax, grid_spacing=10. * u.deg, lw=0.5)
        ax.set_xlabel('')
        ax.set_ylabel('')
        ax.set_xticklabels([])
        ax.set_yticklabels([])
        ax.text(0.5,
                0.5,
                'No Data',
                transform=ax.transAxes,
                color='w',
                ha='center',
                va='center',
                fontsize=120)
        ax.add_patch(rect)
        ax.set_xlim(-1227, 1227)
        ax.set_ylim(-1227, 1227)

        for l, dpi in dpis_dict.items():
            figname = os.path.join(imgoutdir,
                                   '{}_eovsa_bd{:02d}.jpg'.format(l, s + 1))
            fig.savefig(figname, dpi=np.int(dpi), quality=85)
    return
예제 #4
0
def pltBbsoQlookImage(datestr, dpis_dict, fig=None, ax=None, overwrite=False, verbose=False, clearcache=False):
    from astropy.io import fits
    from html.parser import HTMLParser
    class MyHTMLParser(HTMLParser):
        def __init__(self, prefix='bbso_halph_fr_', suffix='.fts'):
            HTMLParser.__init__(self)
            self.prefix = prefix
            self.suffix = suffix

        def handle_starttag(self, tag, attrs):
            if tag != 'a':
                return
            for name, value in attrs:
                if name == "href":
                    if value.startswith(self.prefix) and value.endswith(self.suffix):
                        self.links.append(value)

    def extract(url, prefix='bbso_halph_fr_', suffix='.fts'):
        import urllib.request
        with urllib.request.urlopen(url) as response:
            f = response.read()

        parser = MyHTMLParser(prefix, suffix)
        parser.links = []
        parser.feed(str(f))
        return parser.links

    bbsodir = 'http://www.bbso.njit.edu/pub/archive/'
    plt.ioff()
    dateobj = datetime.strptime(datestr, "%Y-%m-%d")
    datestrdir = dateobj.strftime("%Y/%m/%d/")
    imgindir = os.path.join(imgfitstmpdir, datestr)
    imgoutdir = pltfigdir + datestrdir
    if not os.path.exists(imgindir):
        os.makedirs(imgindir)

    bbsoDataSource = {"_Halph_fr": ["bbso_halph_fr_", ".fts"]}

    if fig is None or ax is None:
        mkfig = True
    else:
        mkfig = False

    if mkfig:
        fig, ax = plt.subplots(figsize=(8, 8))
        fig.subplots_adjust(bottom=0.0, top=1.0, left=0.0, right=1.0)

    if verbose: print('Processing BBSO images for date {}'.format(dateobj.strftime('%Y-%m-%d')))
    for key, sourceid in bbsoDataSource.items():
        fexists = []
        for l, dpi in dpis_dict.items():
            figname = os.path.join(imgoutdir, '{}{}.jpg'.format(l, key))
            fexists.append(os.path.exists(figname))

        if overwrite or (False in fexists):
            bbsosite = os.path.join(bbsodir, datestrdir)
            filelist = extract(bbsosite, sourceid[0], sourceid[1])
            if filelist:
                tfilelist = Time(
                    [datetime.strptime(tf.replace(sourceid[0], '').replace(sourceid[1], ''), "%Y%m%d_%H%M%S") for tf in
                     filelist])
                bbsourl = os.path.join(bbsosite, filelist[
                    np.nanargmin(np.abs(np.array(tfilelist.mjd - (Time(dateobj).mjd + 20. / 24.))))])

                bbsofile = os.path.join(imgindir, key + '.fits')
                if not os.path.exists(bbsofile):
                    try:
                        urllib.request.urlretrieve(bbsourl, bbsofile)
                    except:
                        print('The connection with {} has timed out. Skipped!'.format(bbsourl))
                ax.cla()
                if not os.path.exists(bbsofile): continue
                if not os.path.exists(imgoutdir): os.makedirs(imgoutdir)
                try:
                    hdu = fits.open(bbsofile)[0]
                    header = hdu.header
                    header['WAVELNTH'] = 6562.8
                    header['WAVEUNIT'] = 'angstrom'
                    header['WAVE_STR'] = 'Halph'
                    header['CTYPE1'] = 'HPLN-TAN'
                    header['CUNIT1'] = 'arcsec'
                    header['CTYPE2'] = 'HPLT-TAN'
                    header['CUNIT2'] = 'arcsec'
                    header['DATE-OBS'] = header['DATE_OBS']
                    for k in ['CONTRAST', 'WAVE ERR']:
                        try:
                            header.remove(k)
                        except:
                            pass

                    bbsomap = smap.Map(hdu.data, header)
                    med = np.nanmean(bbsomap.data)
                    norm = colors.Normalize(vmin=med - 1500, vmax=med + 1500)
                    bbsomap_ = pmX.Sunmap(bbsomap)
                    cmap = cm_smap.get_cmap('sdoaia304')
                    bbsomap_.imshow(axes=ax, cmap=cmap, norm=norm)
                    bbsomap_.draw_limb(axes=ax, lw=0.5, alpha=0.5)
                    bbsomap_.draw_grid(axes=ax, grid_spacing=10. * u.deg, lw=0.5)
                    ax.set_xlabel('')
                    ax.set_ylabel('')
                    ax.set_xticklabels([])
                    ax.set_yticklabels([])
                    ax.text(0.02, 0.02,
                            '{}  {}'.format(bbsomap.instrument, bbsomap.date.strftime('%d-%b-%Y %H:%M UT')),
                            transform=ax.transAxes, color='w', ha='left', va='bottom', fontsize=9)
                    ax.set_xlim(-1227, 1227)
                    ax.set_ylim(-1227, 1227)
                    ax.set_facecolor('k')

                    for l, dpi in dpis_dict.items():
                        figname = os.path.join(imgoutdir, '{}{}.jpg'.format(l, key))
                        fig.savefig(figname, dpi=np.int(dpi), quality=85)
                except Exception as err:
                    print('Fail to plot {}'.format(bbsofile))
                    print(err)
    if clearcache:
        os.system('rm -rf ' + imgindir)

    if mkfig:
        pass
    else:
        plt.close(fig)
    return
예제 #5
0
def pltSdoQlookImage(datestr, dpis_dict, fig=None, ax=None, overwrite=False, verbose=False, clearcache=False):
    plt.ioff()
    dateobj = datetime.strptime(datestr, "%Y-%m-%d")
    datestrdir = dateobj.strftime("%Y/%m/%d/")
    imgindir = os.path.join(imgfitstmpdir, datestr)
    imgoutdir = pltfigdir + datestrdir
    if not os.path.exists(imgindir):
        os.makedirs(imgindir)

    aiaDataSource = {"0094": 8,
                     "0193": 11,
                     "0335": 14,
                     # "4500": 17,
                     "0171": 10,
                     "0304": 13,
                     "0131": 9,
                     "1700": 16,
                     "0211": 12,
                     # "1600": 15,
                     "_HMIcont": 18,
                     "_HMImag": 19}

    if fig is None or ax is None:
        mkfig = True
    else:
        mkfig = False

    if mkfig:
        fig, ax = plt.subplots(figsize=(8, 8))
        fig.subplots_adjust(bottom=0.0, top=1.0, left=0.0, right=1.0)

    if verbose: print('Processing SDO images for date {}'.format(dateobj.strftime('%Y-%m-%d')))
    for key, sourceid in aiaDataSource.items():
        fexists = []
        for l, dpi in dpis_dict.items():
            figname = os.path.join(imgoutdir, '{}{}.jpg'.format(l, key))
            fexists.append(os.path.exists(figname))

        if overwrite or (False in fexists):
            sdourl = 'https://api.helioviewer.org/v2/getJP2Image/?date={}T20:00:00Z&sourceId={}'.format(datestr,
                                                                                                        sourceid)
            sdofile = os.path.join(imgindir, key + '.jp2')
            if overwrite and os.path.exists(sdofile):
                os.system('rm -rf {}'.format(sdofile))
            if not os.path.exists(sdofile):
                try:
                    urllib.request.urlretrieve(sdourl, sdofile)
                except:
                    print('The connection with {} has timed out. Skipped!'.format(sdourl))
            ax.cla()

            if not os.path.exists(sdofile): continue
            if not os.path.exists(imgoutdir): os.makedirs(imgoutdir)
            try:
                sdomap = smap.Map(sdofile)
                norm = colors.Normalize()
                sdomap_ = pmX.Sunmap(sdomap)
                if "HMI" in key:
                    cmap = plt.get_cmap('gray')
                else:
                    cmap = cm_smap.get_cmap('sdoaia' + key.lstrip('0'))
                sdomap_.imshow(axes=ax, cmap=cmap, norm=norm)
                sdomap_.draw_limb(axes=ax, lw=0.5, alpha=0.5)
                sdomap_.draw_grid(axes=ax, grid_spacing=10. * u.deg, lw=0.5)
                ax.set_xlabel('')
                ax.set_ylabel('')
                ax.set_xticklabels([])
                ax.set_yticklabels([])
                ax.text(0.02, 0.02,
                        '{}/{} {}  {}'.format(sdomap.observatory, sdomap.instrument.split(' ')[0], sdomap.measurement,
                                              sdomap.date.strftime('%d-%b-%Y %H:%M UT')),
                        transform=ax.transAxes, color='w', ha='left', va='bottom', fontsize=9)
                ax.set_xlim(-1227, 1227)
                ax.set_ylim(-1227, 1227)

                for l, dpi in dpis_dict.items():
                    figname = os.path.join(imgoutdir, '{}{}.jpg'.format(l, key))
                    fig.savefig(figname, dpi=np.int(dpi), quality=85)
            except Exception as err:
                print('Fail to plot {}'.format(sdofile))
                print(err)
    if clearcache:
        os.system('rm -rf ' + imgindir)

    if mkfig:
        pass
    else:
        plt.close(fig)
    return
예제 #6
0
def plt_qlook_image(imres, figdir=None, verbose=True, synoptic=False):
    from matplotlib import pyplot as plt
    from sunpy import map as smap
    from sunpy import sun
    from matplotlib import colors
    import astropy.units as u
    from suncasa.utils import plot_mapX as pmX
    # from matplotlib import gridspec as gridspec

    if not figdir:
        figdir = './'

    nspw = len(set(imres['Spw']))
    plttimes = list(set(imres['BeginTime']))
    ntime = len(plttimes)
    # sort the imres according to time
    images = np.array(imres['ImageName'])
    btimes = Time(imres['BeginTime'])
    etimes = Time(imres['EndTime'])
    spws = np.array(imres['Spw'])
    suc = np.array(imres['Succeeded'])
    inds = btimes.argsort()
    images_sort = images[inds].reshape(ntime, nspw)
    btimes_sort = btimes[inds].reshape(ntime, nspw)
    suc_sort = suc[inds].reshape(ntime, nspw)
    if verbose:
        print('{0:d} figures to plot'.format(ntime))
    plt.ioff()
    fig = plt.figure(figsize=(8, 8))

    plt.subplots_adjust(left=0, bottom=0, right=1, top=1, wspace=0, hspace=0)
    axs = []
    ims = []
    pltst = 0
    for i in range(ntime):
        plt.ioff()
        plttime = btimes_sort[i, 0]
        tofd = plttime.mjd - np.fix(plttime.mjd)
        suci = suc_sort[i]
        if not synoptic:
            if tofd < 16. / 24. or sum(
                    suci
            ) < nspw - 2:  # if time of the day is before 16 UT (and 24 UT), skip plotting (because the old antennas are not tracking)
                continue
            else:
                if pltst == 0:
                    i0 = i
                    pltst = 1
        else:
            if pltst == 0:
                i0 = i
                pltst = 1
        if i == i0:
            if synoptic:
                timetext = fig.text(0.01,
                                    0.98,
                                    plttime.iso[:10],
                                    color='w',
                                    fontweight='bold',
                                    fontsize=12,
                                    ha='left')
            else:
                timetext = fig.text(0.01,
                                    0.98,
                                    plttime.iso[:19],
                                    color='w',
                                    fontweight='bold',
                                    fontsize=12,
                                    ha='left')
        else:
            if synoptic:
                timetext.set_text(plttime.iso[:10])
            else:
                timetext.set_text(plttime.iso[:19])
        if verbose:
            print('Plotting image at: ', plttime.iso)
        for n in range(nspw):
            plt.ioff()
            if i == i0:
                if nspw == 1:
                    ax = fig.add_subplot(111)
                else:
                    ax = fig.add_subplot(nspw / 2, 2, n + 1)
                axs.append(ax)
            else:
                ax = axs[n]
            image = images_sort[i, n]
            if suci[n] or os.path.exists(image):
                try:
                    eomap = smap.Map(image)
                except:
                    continue
                data = eomap.data
                sz = data.shape
                if len(sz) == 4:
                    data = data.reshape((sz[2], sz[3]))
                data[np.isnan(data)] = 0.0
                # add a basin flux to the image to avoid negative values
                data = data + 0.8e5
                data[data < 0] = 0.0
                data = np.sqrt(data)
                eomap = smap.Map(data, eomap.meta)
                # resample the image for plotting
                dim = u.Quantity([256, 256], u.pixel)
                eomap = eomap.resample(dim)
            else:
                # make an empty map
                data = np.zeros((256, 256))
                header = {
                    "DATE-OBS": plttime.isot,
                    "EXPTIME": 0.,
                    "CDELT1": 10.,
                    "NAXIS1": 256,
                    "CRVAL1": 0.,
                    "CRPIX1": 128.5,
                    "CUNIT1": "arcsec",
                    "CTYPE1": "HPLN-TAN",
                    "CDELT2": 10.,
                    "NAXIS2": 256,
                    "CRVAL2": 0.,
                    "CRPIX2": 128.5,
                    "CUNIT2": "arcsec",
                    "CTYPE2": "HPLT-TAN",
                    "HGLT_OBS":
                    sun.heliographic_solar_center(plttime)[1].value,
                    "HGLN_OBS": 0.,
                    "RSUN_OBS":
                    sun.solar_semidiameter_angular_size(plttime).value,
                    "RSUN_REF": sun.constants.radius.value,
                    "DSUN_OBS":
                    sun.sunearth_distance(plttime).to(u.meter).value,
                }
                eomap = smap.Map(data, header)
            if i == i0:
                eomap_ = pmX.Sunmap(eomap)
                # im = eomap_.imshow(axes=ax, cmap='jet', norm=colors.LogNorm(vmin=0.1, vmax=1e8))
                im = eomap_.imshow(axes=ax,
                                   cmap='jet',
                                   norm=colors.Normalize(vmin=150, vmax=700))
                ims.append(im)
                if not synoptic:
                    eomap_.draw_limb(axes=ax)
                eomap_.draw_grid(axes=ax)
                ax.set_xlim([-1080, 1080])
                ax.set_ylim([-1080, 1080])
                try:
                    cfreq = eomap.meta['crval3'] / 1.0e9
                    bdwid = eomap.meta['cdelt3'] / 1.0e9
                    ax.text(0.98,
                            0.01,
                            '{0:.1f} - {1:.1f} GHz'.format(
                                cfreq - bdwid / 2.0, cfreq + bdwid / 2.0),
                            color='w',
                            transform=ax.transAxes,
                            fontweight='bold',
                            ha='right')
                except:
                    pass
                ax.set_title(' ')
                ax.set_xlabel('')
                ax.set_ylabel('')
                ax.set_xticklabels([''])
                ax.set_yticklabels([''])
            else:
                ims[n].set_data(eomap.data)

        fig_tdt = plttime.to_datetime()
        if synoptic:
            fig_subdir = fig_tdt.strftime("%Y/")
            figname = 'eovsa_qlimg_' + plttime.iso[:10].replace('-',
                                                                '') + '.png'
        else:
            fig_subdir = fig_tdt.strftime("%Y/%m/%d/")
            figname = 'eovsa_qlimg_' + plttime.isot.replace(':', '').replace(
                '-', '')[:15] + '.png'
        figdir_ = figdir + fig_subdir
        if not os.path.exists(figdir_):
            os.makedirs(figdir_)
        if verbose:
            print('Saving plot to :' + figdir_ + figname)

        plt.savefig(figdir_ + figname)
    plt.close(fig)
plt_ax = True
for tidx in tqdm(range(len(imres['ImageName']))):
    fsfile = imres['ImageName'][tidx]
    if os.path.exists(fsfile):
        hdu = fits.open(fsfile)
    else:
        data = np.zeros(imsize)
    for s, sp in enumerate(spws):
        cfreq = imres['FreqGHz'][s]
        ax = axs[s]
        if os.path.exists(fsfile):
            data = hdu[0].data[0, s, :, :].reshape(imsize)
            data[np.isnan(data)] = 0.0
            eomap = smap.Map(data, hdu[0].header)
            if tidx == 0 or plt_ax:
                eomap_ = pmX.Sunmap(eomap)
                im.append(
                    eomap_.imshow(axes=ax, vmax=dmaxs[s],
                                  vmin=dmaxs[s] * 0.05))
                eomap_.draw_limb(axes=ax)
                eomap_.draw_grid(axes=ax, grid_spacing=grid_spacing)
            else:
                im[s].set_array(data)
            if tidx == 0:
                ax.text(0.95,
                        0.95,
                        '{0:.1f} GHz'.format(cfreq),
                        transform=ax.transAxes,
                        ha='right',
                        va='top',
                        color='w',
예제 #8
0
def image_adddisk(eofile, diskinfo, edgeconvmode='frommergeddisk', caltbonly=False):
    '''
    :param eofile:
    :param diskxmlfile:
    :param edgeconvmode: available mode: frommergeddisk,frombeam
    :return:
    '''

    from sunpy import map as smap
    from suncasa.utils import plot_mapX as pmX
    from scipy import constants
    import astropy.units as u
    from sunpy import io as sio
    dsize = diskinfo['disk_size']
    fdens = diskinfo['flux_dens']
    freqs = diskinfo['freq']
    eomap = smap.Map(eofile)
    eomap_ = pmX.Sunmap(eomap)
    header = eomap.meta
    bmaj = header['bmaj'] * 3600 * u.arcsec
    bmin = header['bmin'] * 3600 * u.arcsec
    cell = (header['cdelt1'] * u.Unit(header['cunit1']) + header['cdelt2'] * u.Unit(header['cunit2'])) / 2.0
    bmsize = (bmaj + bmin) / 2.0
    data = eomap.data  # remember the data order is reversed due to the FITS convension
    keys = header.keys()
    values = header.values()
    mapx, mapy = eomap_.map2wcsgrids(cell=False)
    mapx = mapx[:-1, :-1]
    mapy = mapy[:-1, :-1]
    rdisk = np.sqrt(mapx ** 2 + mapy ** 2)

    k_b = constants.k
    c_l = constants.c
    const = 2. * k_b / c_l ** 2
    pix_area = (cell.to(u.rad).value) ** 2
    jy_to_si = 1e-26
    factor2 = 1.
    faxis = keys[values.index('FREQ')][-1]

    if caltbonly:
        edgeconvmode = ''
    if edgeconvmode == 'frommergeddisk':

        nul = header['CRVAL' + faxis] + header['CDELT' + faxis] * (1 - header['CRPIX' + faxis])
        nuh = header['CRVAL' + faxis] + header['CDELT' + faxis] * (header['NAXIS' + faxis] - header['CRPIX' + faxis])
        ## get the frequency range of the image
        nu_bound = (np.array([nul, nuh]) + 0.5 * np.array([-1, 1]) * header['CDELT' + faxis]) * u.Unit(
            header['cunit' + faxis])
        nu_bound = nu_bound.to(u.GHz)
        ## get the frequencies of the disk models
        fidxs = np.logical_and(freqs > nu_bound[0], freqs < nu_bound[1])
        ny, nx = rdisk.shape
        freqs_ = freqs[fidxs]
        fdens_ = fdens[fidxs] / 2.0  # divide by 2 because fdens is 2x solar flux density
        dsize_ = dsize[fidxs]
        fdisk_ = np.empty((len(freqs_), ny, nx))
        fdisk_[:] = np.nan
        for fidx, freq in enumerate(freqs_):
            fdisk_[fidx, ...][rdisk <= dsize_[fidx].value] = 1.0
            # nu = header['CRVAL' + faxis] + header['CDELT' + faxis] * (1 - header['CRPIX' + faxis])
            factor = const * freq.to(u.Hz).value ** 2  # SI unit
            jy2tb = jy_to_si / pix_area / factor * factor2
            fdisk_[fidx, ...] = fdisk_[fidx, ...] / np.nansum(fdisk_[fidx, ...]) * fdens_[fidx].value
            fdisk_[fidx, ...] = fdisk_[fidx, ...] * jy2tb
        #         # fdisk_[np.isnan(fdisk_)] = 0.0
        tbdisk = np.nanmean(fdisk_, axis=0)
        tbdisk[np.isnan(tbdisk)] = 0.0

        sig2fwhm = 2.0 * np.sqrt(2 * np.log(2))
        x0, y0 = 0, 0
        sigx, sigy = bmaj.value / sig2fwhm, bmin.value / sig2fwhm
        theta = -(90.0 - header['bpa']) * u.deg
        x = (np.arange(31) - 15) * cell.value
        y = (np.arange(31) - 15) * cell.value
        x, y = np.meshgrid(x, y)
        kernel = gaussian2d(x, y, 1.0, x0, y0, sigx, sigy, theta.to(u.radian).value)
        kernel = kernel / np.nansum(kernel)
        from scipy import signal
        tbdisk = signal.fftconvolve(tbdisk, kernel, mode='same')
    else:
        nu = header['CRVAL' + faxis] + header['CDELT' + faxis] * (1 - header['CRPIX' + faxis])
        freqghz = nu / 1.0e9
        factor = const * nu ** 2  # SI unit
        jy2tb = jy_to_si / pix_area / factor * factor2
        p_dsize = np.poly1d(np.polyfit(freqs.value, dsize.value, 15))
        p_fdens = np.poly1d(
            np.polyfit(freqs.value, fdens.value, 15)) / 2.  # divide by 2 because fdens is 2x solar flux density
        if edgeconvmode == 'frombeam':
            from scipy.special import erfc
            factor_erfc = 2.0  ## erfc function ranges from 0 to 2
            fdisk = erfc((rdisk - p_dsize(freqghz)) / bmsize.value) / factor_erfc
        else:
            fdisk = np.zeros_like(rdisk)
            fdisk[rdisk <= p_dsize(freqghz)] = 1.0
        fdisk = fdisk / np.nansum(fdisk) * p_fdens(freqghz)
        tbdisk = fdisk * jy2tb

    tb_disk = np.nanmax(tbdisk)
    if caltbonly:
        return tb_disk
    else:
        datanew = data + tbdisk
        # datanew[np.isnan(data)] = 0.0
        header['TBDISK'] = tb_disk
        header['TBUNIT'] = 'K'
        eomap_disk = smap.Map(datanew, header)
        nametmp = eofile.split('.')
        nametmp.insert(-1, 'disk')
        outfits = '.'.join(nametmp)
        datanew = datanew.astype(np.float32)
        if os.path.exists(outfits):
            os.system('rm -rf {}'.format(outfits))
        sio.write_file(outfits, datanew, header)
        return eomap_disk, tb_disk, outfits