if os.path.exists(fsfile):
        hdu.close()
        plt_ax = False

    if tidx == 0:
        ax = axs[0]
        timetext = ax.text(0.95,
                           0.02,
                           eomap.date.strftime('%H:%M:%S'),
                           ha='right',
                           va='bottom',
                           transform=ax.transAxes,
                           color='w',
                           fontweight='bold')
    else:
        timetext.set_text(eomap.date.strftime('%H:%M:%S'))

    tim_axvspan_xy = tim_axvspan.get_xy()
    tim_axvspan_xy[np.array([0, 1, 4]),
                   0] = Time(imres['BeginTime'][tidx]).plot_date
    tim_axvspan_xy[np.array([2, 3]),
                   0] = Time(imres['EndTime'][tidx]).plot_date
    tim_axvspan.set_xy(tim_axvspan_xy)
    # tim_axvspan.set_xy(tim_axvspan_xy)
    figname = fsfile[:-9] + '.png'
    fig.savefig(figname, dpi=100)

plt.ion()

DButil.img2html_movie('{}/EO'.format(outdir))
Exemplo n.º 2
0
def plt_qlook_image(imres, figdir=None, specdata=None, verbose=True, stokes='I,V', fov=None):
    from matplotlib import pyplot as plt
    from sunpy import map as smap
    from sunpy import sun
    import astropy.units as u
    if not figdir:
        figdir = './'

    observatory = 'EOVSA'
    polmap = {'RR': 0, 'LL': 1, 'I': 0, 'V': 1}
    pols = stokes.split(',')
    npols = len(pols)
    # SRL = set(['RR', 'LL'])
    # SXY = set(['XX', 'YY', 'XY', 'YX'])
    Spw = sorted(list(set(imres['Spw'])))
    nspw = len(Spw)
    # Freq = set(imres['Freq']) ## list is an unhashable type
    Freq = sorted(uniq(imres['Freq']))

    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)
    spws_sort = spws[inds].reshape(ntime, nspw)
    if verbose:
        print '{0:d} figures to plot'.format(ntime)
    plt.ioff()
    import matplotlib.gridspec as gridspec
    spec = specdata['spec']
    (npol, nbl, nfreq, ntim) = spec.shape
    tidx = range(ntim)
    fidx = range(nfreq)
    tim = specdata['tim']
    freq = specdata['freq']
    freqghz = freq / 1e9
    pol = ''.join(pols)
    spec_tim = Time(specdata['tim'] / 3600. / 24., format='mjd')
    timstrr = spec_tim.plot_date
    if npols == 1:
        if pol == 'RR':
            spec_plt = spec[0, 0, :, :]
        elif pol == 'LL':
            spec_plt = spec[1, 0, :, :]
        elif pol == 'I':
            spec_plt = (spec[0, 0, :, :] + spec[1, 0, :, :]) / 2.
        elif pol == 'V':
            spec_plt = (spec[0, 0, :, :] - spec[1, 0, :, :]) / 2.
        spec_plt = [spec_plt]
        print 'plot the dynamic spectrum in pol ' + pol  # ax1 = fig.add_subplot(211)

        hnspw = nspw / 2
        ncols = hnspw
        nrows = 2 + 2  # 1 image: 1x1, 1 dspec:2x4
        fig = plt.figure(figsize=(8, 8))
        gs = gridspec.GridSpec(nrows, ncols)
        axs = [plt.subplot(gs[0, 0])]
        for ll in range(1, nspw):
            axs.append(plt.subplot(gs[ll / hnspw, ll % hnspw], sharex=axs[0], sharey=axs[0]))
        for ll in range(nspw):
            axs.append(plt.subplot(gs[ll / hnspw + 2, ll % hnspw], sharex=axs[0], sharey=axs[0]))
        axs_dspec = [plt.subplot(gs[2:, :])]
        cmaps = ['jet']
    elif npols == 2:
        R_plot = np.absolute(spec[0, 0, :, :])
        L_plot = np.absolute(spec[1, 0, :, :])
        if pol == 'RRLL':
            spec_plt = [R_plot, L_plot]
            polstr = ['RR', 'LL']
            cmaps = ['jet'] * 2
        if pol == 'IV':
            I_plot = (R_plot + L_plot) / 2.
            V_plot = (R_plot - L_plot) / 2.
            spec_plt = [I_plot, V_plot]
            polstr = ['I', 'V']
            cmaps = ['jet', 'RdBu']
        print 'plot the dynamic spectrum in pol ' + pol

        hnspw = nspw / 2
        ncols = hnspw + 2  # 1 image: 1x1, 1 dspec:2x2
        nrows = 2 + 2
        fig = plt.figure(figsize=(12, 8))
        gs = gridspec.GridSpec(nrows, ncols)
        axs = [plt.subplot(gs[0, 0])]
        for ll in range(1, nspw):
            axs.append(plt.subplot(gs[ll / hnspw, ll % hnspw], sharex=axs[0], sharey=axs[0]))
        for ll in range(nspw):
            axs.append(plt.subplot(gs[ll / hnspw + 2, ll % hnspw], sharex=axs[0], sharey=axs[0]))
        axs_dspec = [plt.subplot(gs[:2, hnspw:])]
        axs_dspec.append(plt.subplot(gs[2:, hnspw:], sharex=axs_dspec[0], sharey=axs_dspec[0]))

    fig.subplots_adjust(left=0, bottom=0, right=1, top=1, wspace=0, hspace=0)
    timetext = fig.text(0.01, 0.98, '', color='w', fontweight='bold', fontsize=12, ha='left', va='top')
    for i in range(ntime):
        plt.ioff()
        # plt.clf()
        for ax in axs:
            ax.cla()
        plttime = btimes_sort[i, 0]
        # tofd = plttime.mjd - np.fix(plttime.mjd)
        suci = suc_sort[i]
        # 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
        # fig=plt.figure(figsize=(9,6))
        # fig.suptitle('EOVSA @ '+plttime.iso[:19])
        timetext.set_text(plttime.iso[:19])
        if verbose:
            print 'Plotting image at: ', plttime.iso

        if i == 0:
            dspecvspans = []
            for pol in range(npols):
                ax = axs_dspec[pol]
                ax.pcolormesh(timstrr, freqghz, spec_plt[pol], cmap=cmaps[pol])
                ax.xaxis_date()
                ax.xaxis.set_major_formatter(DateFormatter("%H:%M:%S"))
                # plt.xticks(rotation=45)
                ax.set_xlim(timstrr[tidx[0]], timstrr[tidx[-1]])
                ax.set_ylim(freqghz[fidx[0]], freqghz[fidx[-1]])
                ax.set_xlabel('Time [UT]')
                ax.set_ylabel('Frequency [GHz]')
                for idx, freq in enumerate(Freq):
                    ax.axhspan(freq[0], freq[1], linestyle='dotted', edgecolor='w', alpha=0.7, facecolor='none')
                    xtext, ytext = ax.transAxes.inverted().transform(ax.transData.transform([timstrr[tidx[0]], np.mean(freq)]))
                    ax.text(xtext + 0.01, ytext, 'spw ' + Spw[idx], color='w', transform=ax.transAxes, fontweight='bold', ha='left', va='center',
                            fontsize=8, alpha=0.5)
                ax.text(0.01, 0.98, 'Stokes ' + pols[pol], color='w', transform=ax.transAxes, fontweight='bold', ha='left', va='top')
                dspecvspans.append(ax.axvspan(btimes[i].plot_date, etimes[i].plot_date, color='w', alpha=0.4))
                ax_pos = ax.get_position().extents
                x0, y0, x1, y1 = ax_pos
                h, v = x1 - x0, y1 - y0
                x0_new = x0 + 0.15 * h
                y0_new = y0 + 0.15 * v
                x1_new = x1 - 0.05 * h
                y1_new = y1 - 0.05 * v
                ax.set_position(mpl.transforms.Bbox([[x0_new, y0_new], [x1_new, y1_new]]))
        else:
            for pol in range(npols):
                xy = dspecvspans[pol].get_xy()
                xy[:, 0][np.array([0, 1, 4])] = btimes[i].plot_date
                xy[:, 0][np.array([2, 3])] = etimes[i].plot_date
                dspecvspans[pol].set_xy(xy)

        for n in range(nspw):
            image = images_sort[i, n]
            # fig.add_subplot(nspw/3, 3, n+1)
            # fig.add_subplot(2, nspw / 2, n + 1)
            for pol in range(npols):
                if suci[n]:
                    try:
                        eomap = smap.Map(image)
                    except:
                        continue
                    sz = eomap.data.shape
                    if len(sz) == 4:
                        eomap.data = eomap.data[min(polmap[pols[pol]], eomap.meta['naxis4'] - 1), 0, :, :].reshape((sz[2], sz[3]))
                    # resample the image for plotting
                    if fov is not None:
                        fov = [np.array(ll) for ll in fov]
                        pad = max(np.diff(fov[0])[0], np.diff(fov[1])[0])
                        eomap = eomap.submap((fov[0] + np.array([-1.0, 1.0]) * pad) * u.arcsec, (fov[1] + np.array([-1.0, 1.0]) * pad) * u.arcsec)
                    else:
                        dim = u.Quantity([256, 256], u.pixel)
                        eomap = eomap.resample(dim)
                    eomap.plot_settings['cmap'] = plt.get_cmap(cmaps[pol])
                    # import pdb
                    # pdb.set_trace()
                    eomap.plot(axes=axs[n + nspw * pol])
                    eomap.draw_limb()
                    eomap.draw_grid()
                    ax = plt.gca()
                    ax.set_autoscale_on(False)
                    if fov:
                        # pass
                        ax.set_xlim(fov[0])
                        ax.set_ylim(fov[1])
                    else:
                        ax.set_xlim([-1080, 1080])
                        ax.set_ylim([-1080, 1080])
                    spwran = spws_sort[i, n]
                    # freqran = [int(s) * 0.5 + 2.9 for s in spwran.split('~')]
                    # if len(freqran) == 1:
                    #     ax.text(0.98, 0.01, '{0:.1f} GHz'.format(freqran[0]), color='w',
                    #             transform=ax.transAxes, fontweight='bold', ha='right')
                    # else:
                    #     ax.text(0.98, 0.01, '{0:.1f} - {1:.1f} GHz'.format(freqran[0], freqran[1]), color='w',
                    #             transform=ax.transAxes, fontweight='bold', ha='right')
                    ax.text(0.98, 0.01, 'Stokes {1} @ {0:.3f} GHz'.format(eomap.meta['crval3'] / 1e9, pols[pol]), color='w', transform=ax.transAxes,
                            fontweight='bold', ha='right')
                    ax.set_title(' ')
                    # ax.set_title('spw '+spws_sort[i,n])
                    # ax.text(0.01,0.02, plttime.isot,transform=ax.transAxes,color='white')
                    ax.xaxis.set_visible(False)
                    ax.yaxis.set_visible(False)
                else:
                    # make an empty map
                    data = np.zeros((512, 512))
                    header = {"DATE-OBS": plttime.isot, "EXPTIME": 0., "CDELT1": 5., "NAXIS1": 512, "CRVAL1": 0., "CRPIX1": 257, "CUNIT1": "arcsec",
                              "CTYPE1": "HPLN-TAN", "CDELT2": 5., "NAXIS2": 512, "CRVAL2": 0., "CRPIX2": 257, "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)
                    # resample the image for plotting
                    if fov:
                        fov = [np.array(ll) for ll in fov]
                        pad = max(np.diff(fov[0])[0], np.diff(fov[1])[0])
                        try:
                            eomap = eomap.submap((fov[0] + np.array([-1.0, 1.0]) * pad) * u.arcsec, (fov[1] + np.array([-1.0, 1.0]) * pad) * u.arcsec)
                        except:
                            x0, x1 = fov[0] + np.array([-1.0, 1.0]) * pad
                            y0, y1 = fov[1] + np.array([-1.0, 1.0]) * pad
                            bl = SkyCoord(x0 * u.arcsec, y0 * u.arcsec, frame=eomap.coordinate_frame)
                            tr = SkyCoord(x1 * u.arcsec, y1 * u.arcsec, frame=eomap.coordinate_frame)
                            eomap = eomap.submap(bl, tr)
                    else:
                        dim = u.Quantity([256, 256], u.pixel)
                        eomap = eomap.resample(dim)
                    eomap.plot_settings['cmap'] = plt.get_cmap(cmaps[pol])
                    eomap.plot(axes=axs[n + nspw * pol])
                    eomap.draw_limb()
                    eomap.draw_grid()
                    ax = plt.gca()
                    ax.set_autoscale_on(False)
                    if fov:
                        # pass
                        ax.set_xlim(fov[0])
                        ax.set_ylim(fov[1])
                    else:
                        ax.set_xlim([-1080, 1080])
                        ax.set_ylim([-1080, 1080])
                    # ax.set_title('spw '+spwran+'( )'))
                    spwran = spws_sort[i, n]
                    freqran = [int(s) * 0.5 + 2.9 for s in spwran.split('~')]
                    spwran = spws_sort[i, n]
                    # ax.set_title('{0:.1f} - {1:.1f} GHz'.format(freqran[0],freqran[1]))
                    # ax.text(0.98, 0.01, '{0:.1f} - {1:.1f} GHz'.format(freqran[0], freqran[1]), color='w',
                    #         transform=ax.transAxes, fontweight='bold', ha='right')
                    ax.text(0.98, 0.01, 'Stokes {1} @ {0:.3f} GHz'.format(0., pols[pol]), color='w', transform=ax.transAxes, fontweight='bold',
                            ha='right')
                    ax.set_title(' ')

                    # ax.text(0.01,0.02, plttime.isot,transform=ax.transAxes,color='white')
                    ax.xaxis.set_visible(False)
                    ax.yaxis.set_visible(False)
        figname = observatory + '_qlimg_' + plttime.isot.replace(':', '').replace('-', '')[:19] + '.png'
        fig_tdt = plttime.to_datetime()
        # fig_subdir = fig_tdt.strftime("%Y/%m/%d/")
        figdir_ = figdir  # + fig_subdir
        if not os.path.exists(figdir_):
            os.makedirs(figdir_)
        if verbose:
            print 'Saving plot to: ' + os.path.join(figdir_, figname)
        plt.savefig(os.path.join(figdir_, figname))
    plt.close(fig)
    DButil.img2html_movie(figdir_)