Пример #1
0
 def interpolate(self, new_mlat_grid, new_mlt_grid ,method='nearest'):
     """
     Rectangularize and Interpolate (using Linear 2D interpolation)
     """
     X0, Y0 = satplottools.latlt2cart(self.mlat_orig.flatten(), self.mlt_orig.flatten(),self.hemisphere)
     X, Y = satplottools.latlt2cart(new_mlat_grid.flatten(), new_mlt_grid.flatten(),self.hemisphere)
     interpd_zvar = interpolate.griddata((X0,Y0), self.zvar.flatten(), (X,Y), method=method, fill_value=0.)
     return interpd_zvar.reshape(new_mlat_grid.shape)
Пример #2
0
def draw_conductance(dt, startdt, enddt, hemi):
    """
    Get the hall and pedersen conductance for one date and hemisphere
    """
    estimator = ovation_prime.ConductanceEstimator(startdt, enddt)

    mlatgrid, mltgrid, pedgrid, hallgrid = estimator.get_conductance(
        dt, hemi=hemi, auroral=True, solar=True)

    f = pp.figure(figsize=(11, 5))
    aH = f.add_subplot(121)
    aP = f.add_subplot(122)

    X, Y = satplottools.latlt2cart(mlatgrid.flatten(), mltgrid.flatten(), hemi)
    X = X.reshape(mlatgrid.shape)
    Y = Y.reshape(mltgrid.shape)

    satplottools.draw_dialplot(aH)
    satplottools.draw_dialplot(aP)

    mappableH = aH.pcolormesh(X, Y, hallgrid, vmin=0., vmax=20.)
    mappableP = aP.pcolormesh(X, Y, pedgrid, vmin=0., vmax=15.)

    aH.set_title("Hall Conductance")
    aP.set_title("Pedersen Conductance")

    f.colorbar(mappableH, ax=aH)
    f.colorbar(mappableP, ax=aP)

    f.suptitle(
        "OvationPyme Conductance Output {0} Hemisphere at {1} \n".format(
            hemi, dt.strftime('%c')),
        fontweight='bold')
    return f
Пример #3
0
def draw_weighted_flux(dt, atype='diff', jtype='electron energy flux'):
    """
    Test automatic generation of omni_intervals in ovation_utilities
    also by not specifying a start and end time for the FluxEstimator
    """
    estimator = ovation_prime.FluxEstimator(atype, jtype)

    mlatgridN, mltgridN, fluxgridN = estimator.get_flux_for_time(dt, hemi='N')
    mlatgridS, mltgridS, fluxgridS = estimator.get_flux_for_time(dt, hemi='S')

    f = pp.figure(figsize=(11, 5))
    aN = f.add_subplot(121)
    aS = f.add_subplot(122)

    XN, YN = satplottools.latlt2cart(mlatgridN.flatten(), mltgridN.flatten(),
                                     'N')
    XS, YS = satplottools.latlt2cart(mlatgridS.flatten(), mltgridS.flatten(),
                                     'S')

    XN = XN.reshape(mlatgridN.shape)
    YN = YN.reshape(mltgridN.shape)
    XS = XS.reshape(mlatgridS.shape)
    YS = YS.reshape(mltgridS.shape)

    satplottools.draw_dialplot(aN)
    satplottools.draw_dialplot(aS)

    mappableN = aN.pcolormesh(XN, YN, fluxgridN, vmin=0, vmax=2)
    mappableS = aS.pcolormesh(XS, YS, fluxgridS, vmin=0, vmax=2)

    #aN.set_title("Northern Hemisphere Flux")
    #aS.set_title("Southern Hemisphere Flux")

    f.colorbar(mappableN, ax=aN)
    f.colorbar(mappableS, ax=aS)

    f.suptitle(
        "OvationPyme Auroral Model Flux Output at {0} \n AuroralType:{1}, FluxType:{2}"
        .format(dt.strftime('%c'), atype, jtype),
        fontweight='bold')
    return f
Пример #4
0
def draw_interpolated_conductance(new_mlat_grid, new_mlt_grid, dt, startdt,
                                  enddt, hemi):
    """
    Interpolate hall and pedersen conductance
    onto grid described by mlat_grid, mlt_grid
    """
    estimator = ovation_prime.ConductanceEstimator(startdt, enddt)

    mlatgrid, mltgrid, pedgrid, hallgrid = estimator.get_conductance(
        dt, hemi=hemi, auroral=True, solar=True)

    ped_interpolator = ovation_prime.LatLocaltimeInterpolator(
        mlatgrid, mltgrid, pedgrid)
    new_pedgrid = ped_interpolator.interpolate(new_mlat_grid, new_mlt_grid)

    hall_interpolator = ovation_prime.LatLocaltimeInterpolator(
        mlatgrid, mltgrid, hallgrid)
    new_hallgrid = hall_interpolator.interpolate(new_mlat_grid, new_mlt_grid)

    f = pp.figure(figsize=(11, 5))
    aH = f.add_subplot(121)
    aP = f.add_subplot(122)

    X, Y = satplottools.latlt2cart(new_mlat_grid.flatten(),
                                   new_mlt_grid.flatten(), hemi)
    X = X.reshape(new_mlat_grid.shape)
    Y = Y.reshape(new_mlt_grid.shape)

    satplottools.draw_dialplot(aH)
    satplottools.draw_dialplot(aP)

    mappableH = aH.pcolormesh(X, Y, new_hallgrid, vmin=0., vmax=20.)
    mappableP = aP.pcolormesh(X, Y, new_pedgrid, vmin=0., vmax=15.)

    aH.set_title("Hall Conductance")
    aP.set_title("Pedersen Conductance")

    f.colorbar(mappableH, ax=aH)
    f.colorbar(mappableP, ax=aP)

    f.suptitle(
        "OvationPyme Interpolated Conductance {0} Hemisphere at {1}".format(
            hemi, dt.strftime('%c')),
        fontweight='bold')
    return f
Пример #5
0
def draw_seasonal_flux(seasonN='summer',
                       seasonS='winter',
                       atype='diff',
                       jtype='electron energy flux',
                       dF=2134.17):
    dF = 2134.17

    estimatorN = ovation_prime.SeasonalFluxEstimator(seasonN, atype, jtype)
    estimatorS = ovation_prime.SeasonalFluxEstimator(seasonS, atype, jtype)

    fluxtupleN = estimatorN.get_gridded_flux(dF, combined_N_and_S=False)
    (mlatgridN, mltgridN, fluxgridN) = fluxtupleN[:3]

    fluxtupleS = estimatorS.get_gridded_flux(dF, combined_N_and_S=False)
    (mlatgridS, mltgridS, fluxgridS) = fluxtupleS[3:]

    f = pp.figure(figsize=(11, 5))
    aN = f.add_subplot(121)
    aS = f.add_subplot(122)

    f2 = pp.figure(figsize=(5, 5))
    a2 = f2.add_subplot(111)

    XN, YN = satplottools.latlt2cart(mlatgridN.flatten(), mltgridN.flatten(),
                                     'N')
    XS, YS = satplottools.latlt2cart(mlatgridS.flatten(), mltgridS.flatten(),
                                     'S')

    XN = XN.reshape(mlatgridN.shape)
    YN = YN.reshape(mltgridN.shape)
    XS = XS.reshape(mlatgridS.shape)
    YS = YS.reshape(mltgridS.shape)

    satplottools.draw_dialplot(aN)
    satplottools.draw_dialplot(aS)
    satplottools.draw_dialplot(a2)

    mappableN = aN.pcolormesh(XN, YN, fluxgridN, vmin=0, vmax=2)
    mappableS = aS.pcolormesh(XS, YS, fluxgridS, vmin=0, vmax=2)
    mappableNS = a2.pcolormesh(XN,
                               YN, (fluxgridS + fluxgridN) / 2,
                               vmin=0,
                               vmax=2)

    #aN.set_title("Northern Hemisphere Flux")
    #aS.set_title("Southern Hemisphere Flux")

    f.colorbar(mappableN, ax=aN)
    f.colorbar(mappableS, ax=aS)
    f.colorbar(mappableNS, ax=a2)

    f.suptitle(
        "OvationPyme Auroral Model Raw Flux Output \n Season:{0}, AuroralType:{1}, FluxType:{2}, Newell Coupling:{3:.3f}"
        .format(seasonN, atype, jtype, dF),
        fontweight='bold')

    f2.suptitle(
        "OvationPyme Combined Hemisphere Output \n Season:{0}, AuroralType:{1}, FluxType:{2}, Newell Coupling:{3:.3f}"
        .format(seasonN, atype, jtype, dF),
        fontweight='bold')

    return f, f2
Пример #6
0
    def plot(self):
        """ Draw a dialplot of the data
        """

        f = pp.figure(figsize=(8.5, 11), dpi=300)
        a = f.add_subplot(3, 1, 1)
        a2 = f.add_subplot(3, 1, 2)
        a3 = f.add_subplot(3, 1, 3)

        iflx = self['intflux']
        iflx[iflx == 0.] = .1

        ms = 2

        #Plot the track
        X, Y = satplottools.latlt2cart(self['mlat'], self['mlt'], self.hemi)
        a.plot(X, Y, 'k.', markersize=ms)

        mappable = satplottools.hairplot(a,
                                         self['mlat'],
                                         self['mlt'],
                                         np.log10(self['intflux']),
                                         self.hemi,
                                         vmin=np.log10(self.FLUX_MIN),
                                         vmax=12)
        f.colorbar(mappable,
                   label='log$_{10}$(Smoothed Integrated EEFlux)',
                   ax=a)

        titlstr = "%s\n" % (os.path.split(self.satday.cdffn)[1])

        a.text(0, 0, self.hemi)
        #def dmsp_spectrogram( times, flux, channel_energies, lat=None, lt=None, fluxunits='eV/cm^2-s-sr-eV',
        #        logy=True, datalabel=None, cblims=None, title=None, ax=None, ax_cb=None ):

        fluxstd = self.moving_average(self['total_flux_std'], 15)
        a2.plot(self['uts'],
                self['intflux'],
                'k.',
                label='Smoothed Int >1KeV Flx',
                ms=5.)
        a2.plot(self['uts'], fluxstd, 'r.', ms=3, label='Relative Uncertainty')
        #a2.axhline(np.nanmean(fluxstd)-.5*np.nanstd(fluxstd),label='Mean Uncertainty',color='orange')
        #a2.plot(self['uts'],self['intflux']-3*self['intflux']*fluxstd,'g.',ms=5,label='3*std lower bound')
        a2.set_xlabel("UT Second of Day")
        a2.set_yscale('log')
        a2.axhline(self.FLUX_MIN, label='Threshold', color='grey')
        a2_title = "Integrated Flux (9 Highest E Channels %.2feV-%.2feV)" % (
            self['channel_energies'][0], self['channel_energies'][8])
        a2.set_title(a2_title, fontsize="medium")

        dmsp_spectrogram.dmsp_spectrogram(self['time'],
                                          self['diff_flux'],
                                          self['channel_energies'],
                                          lat=self['mlat'],
                                          lt=self['mlt'],
                                          ax=a3,
                                          cblims=[1e5, 1e10])
        #a3.set_ylim([1e2,1e5])

        if self.segments is not None:
            for seg in self.segments:
                a2.axvspan(seg['uts'][0],
                           seg['uts'][-1],
                           facecolor='m',
                           alpha=.2)

        a2.grid(True)
        a3.grid(True)

        lw = 1.5
        txtshift = 5
        #Add boundaries
        if self.idx_equator1 is not None:
            a.plot(X[self.idx_equator1], Y[self.idx_equator1], 'bo', alpha=.5)
            a2.axvline(self['uts'][self.idx_equator1],
                       color='b',
                       label='EQ1',
                       lw=lw)
            a3.axvline(self['time'][self.idx_equator1],
                       color='b',
                       label='EQ1',
                       lw=lw)
            a.text(X[self.idx_equator1],
                   Y[self.idx_equator1] - txtshift,
                   "EQ1",
                   color='b',
                   horizontalalignment='left')
        else:
            titlstr += 'No 1st EQB,'

        if self.idx_pole1 is not None:
            a.plot(X[self.idx_pole1], Y[self.idx_pole1], 'ro', alpha=.5)
            a2.axvline(self['uts'][self.idx_pole1],
                       color='r',
                       label='PO1',
                       lw=lw)
            a3.axvline(self['time'][self.idx_pole1],
                       color='r',
                       label='PO1',
                       lw=lw)
            a.text(X[self.idx_pole1],
                   Y[self.idx_pole1] - txtshift,
                   "PO1",
                   color='r',
                   horizontalalignment='right')
        else:
            titlstr += 'No 1st PWB,'

        if self.idx_pole2 is not None:
            a.plot(X[self.idx_pole2],
                   Y[self.idx_pole2],
                   'o',
                   color='m',
                   alpha=.5)
            a2.axvline(self['uts'][self.idx_pole2],
                       color='m',
                       label='PO2',
                       lw=lw)
            a3.axvline(self['time'][self.idx_pole2],
                       color='m',
                       label='PO2',
                       lw=lw)
            a.text(X[self.idx_pole2],
                   Y[self.idx_pole2] - txtshift,
                   "PO2",
                   color='m',
                   horizontalalignment='left')
        else:
            titlstr += 'No 2nd PWB,'

        if self.idx_equator2 is not None:
            a.plot(X[self.idx_equator2],
                   Y[self.idx_equator2],
                   'o',
                   color='deepskyblue',
                   alpha=.5)
            a2.axvline(self['uts'][self.idx_equator2],
                       color='deepskyblue',
                       label='EQ2',
                       lw=lw)
            a3.axvline(self['time'][self.idx_equator2],
                       color='deepskyblue',
                       label='EQ2',
                       lw=lw)
            a.text(X[self.idx_equator2],
                   Y[self.idx_equator2] - txtshift,
                   "EQ2",
                   color='deepskyblue',
                   horizontalalignment='right')
        else:
            titlstr += 'No 2nd EQB,'

        if titlstr[-1] == ',':
            titlstr = titlstr[:-1] + '\n'  # Remove trailing comma, add newline

        #a.legend(ncol=2, fontsize="medium")
        a2.legend(loc=0, fontsize="medium")

        if self.failure_reason is not None:
            a.text(-40, -60, self.failure_reason, color='red')
        else:
            desc = "Boundary 1: %.3f-%.3f, A: %.1e, RelUncertA: %.1f, A/A_max: %.3f, twidth: %.3fs\n" % (
                self['mlat'][self.idx_equator1], self['mlat'][self.idx_pole1],
                self.segment1.area, self.segment1.area_uncert,
                self.segment1.area / self.max_seg_area, self.segment1.twidth)
            desc += "Boundary 2: %.3f-%.3f,A: %.1e, RelUncertA: %.1f, A/A_max: %.3f, twidth: %.3fs\n" % (
                self['mlat'][self.idx_equator2], self['mlat'][self.idx_pole2],
                self.segment2.area, self.segment2.area_uncert,
                self.segment2.area / self.max_seg_area, self.segment2.twidth)
            desc += "Polar Cap Width in Time %.1f sec" % (
                self.segment2['uts'][0] - self.segment1['uts'][-1])
            a.text(-60., -60., desc, color='blue', fontsize="x-small")

        if self.max_fom is not None:
            titlstr += 'Identification FOM ( < 1.8 is questionable ): %.2f' % (
                self.max_fom)

        f.suptitle(titlstr, fontsize="medium")

        #f.autofmt_xdate()
        #f.tight_layout()
        f.subplots_adjust(top=.94, hspace=.3, left=.15)

        return f
def plot_orbit_cond(sat, year, month, day, orbit, minlat=50., plotdir=None):

    #
    #Prepare Plots
    #
    import matplotlib.gridspec as gridspec
    from matplotlib.colors import LogNorm

    gs = gridspec.GridSpec(4, 11)
    f = pp.figure()
    #a0 = f.add_subplot(511)
    #a05 = f.add_subplot(512)
    split = 9
    cbwidth = 1
    a1 = pp.subplot(gs[0, :split])
    a11 = pp.subplot(gs[0, split:split + cbwidth])
    a2 = pp.subplot(gs[1, :split])
    a22 = pp.subplot(gs[1:2, split:])
    a3 = pp.subplot(gs[2, :split])
    #a33 = pp.subplot(gs[2,split:])
    a4 = pp.subplot(gs[3, :split])
    a44 = pp.subplot(gs[3, split:split + cbwidth])

    #
    # Get conductance CDF
    #
    cdffn = get_cdf(sat,
                    year,
                    month,
                    day,
                    'ssj',
                    cdfdir=cdfdir,
                    return_file=True)
    cdffn_cond = get_cond_cdffn(cdffn)
    cdffn_cond_leaf = os.path.split(cdffn_cond)[-1]
    cdffn_cond_leaf = os.path.splitext(cdffn_cond_leaf)[0]

    hemi = 'N' if np.sign(orbit) == 1 else 'S'

    #
    #   Figure Filename
    #
    if plotdir is None:
        plotdir = '/home/liamk/code/glowcond/%s' % (cdffn_cond_leaf)
    if not os.path.exists(plotdir):
        os.makedirs(plotdir)

    figfn = os.path.join(
        plotdir, '%s_%s_%d.png' % (cdffn_cond_leaf, hemi, np.abs(orbit)))

    with pycdf.CDF(cdffn_cond) as cdf:

        orbit_index = cdf['ORBIT_INDEX'][:].flatten()
        mlats = cdf['SC_APEX_LAT'][:].flatten()

        in_orbit = orbit_index == orbit
        subset = np.logical_and(in_orbit, np.abs(mlats) > minlat)

        dts = cdf['Epoch'][:][subset]
        uts = special_datetime.datetimearr2sod(
            cdf['Epoch'][:]).flatten()[subset]
        hod = uts / 3600.
        auroral_region = cdf['AURORAL_REGION'][:].flatten()[subset]
        chen = cdf['CHANNEL_ENERGIES'][:]
        glats = cdf['SC_GEOCENTRIC_LAT'][:].flatten()[subset]
        glons = cdf['SC_GEOCENTRIC_LON'][:].flatten()[subset]
        mlats = cdf['SC_APEX_LAT'][:].flatten()[subset]
        mlts = cdf['SC_APEX_MLT'][:].flatten()[subset]

        eflux = cdf['ELE_DIFF_ENERGY_FLUX'][:][subset, :]
        avg_energy = cdf['ELE_AVG_ENERGY'][:].flatten()[subset]
        total_eflux = cdf['ELE_TOTAL_ENERGY_FLUX'][:].flatten()[subset]

        total_eflux *= 1.6e-12  #eV/cm/s/sr -> mW/m^2
        eflux *= 1.6e-12

        z = cdf['CONDUCTIVITY_ALTITUDES'][:]
        ped = cdf['PEDERSEN_CONDUCTIVITY'][:][subset]
        hall = cdf['HALL_CONDUCTIVITY'][:][subset]
        intped = cdf['PEDERSEN_CONDUCTANCE'][:][subset]
        inthall = cdf['HALL_CONDUCTANCE'][:][subset]

        if spectrograms:
            #Plot Electron energy flux
            dmsp_spectrogram.dmsp_spectrogram(
                hod,
                eflux,
                chen,
                datalabel=None,
                cblims=[1e-7, 1e-2],
                ax=a1,
                ax_cb=a11,
                fluxunits='Electron\nEnergy Flux\n[mW/m^2]')

        #Plot Pedersen Conductance
        a2.plot(hod, intped, 'r.-', label='DMSP+GLOW')
        #a2.plot(uts[:-1],np.diff(inthall),label='dPed')
        #a2.set_ylim([0,120])
        #a2.set_ylim([0,1])
        a2.legend(ncol=2, loc=0)
        a2.set_ylabel('Pedersen\n Conductance\n[S]')

        satplottools.draw_dialplot(a22)
        x, y = satplottools.latlt2cart(mlats, mlts, hemi)
        a22.plot(x, y, 'k.')
        a22.text(x[-1], y[-1], 'End')

        #Plot Hall Conductance
        a3.plot(hod, inthall, 'r.-', label='DMSP+GLOW')
        a3.legend(ncol=2, loc=0)
        a3.set_ylabel('Hall\n Conductance\n[S]')

        #Draw conductivity as a pcolor plot with log-scaled color scale
        try:
            ped[ped <= 0.] = 0.01
            T, Z = np.meshgrid(hod, z)
            mappable = a4.pcolor(T,
                                 Z,
                                 ped.T,
                                 norm=LogNorm(vmin=np.nanmin(ped),
                                              vmax=np.nanmax(ped)),
                                 cmap='jet')
            cb = pp.colorbar(mappable, cax=a44)
            cb.ax.set_ylabel('Pedersen\nConductivity\n [S/m]')
            a4.set_ylabel('Altitude\n[km]')
        except:
            pass

        for ax in [a1, a2, a3]:
            ax.xaxis.set_ticklabels([])

        for ax in [a1, a2, a3, a4]:
            ax.set_xlim(hod[0], hod[-1])

        a4.set_xlabel('Hour of Day')

        f.suptitle('%.2d-%2.d-%d %s orbit %d' %
                   (year, month, day, hemi, orbit))

        f.savefig(figfn)
        pp.close(f)
Пример #8
0
        cblims=[1e-7, 1e-2],
        ax=a1,
        ax_cb=a11,
        fluxunits='Electron\nEnergy Flux\n[mW/m^2]')

    #Plot Pedersen Conductance
    a2.plot(uts, intped, 'r.-', label='DMSP+GLOW')
    a2.plot(uts, cond_ped_op, 'b.-', label='OP2010+Robinson')
    #a2.plot(uts[:-1],np.diff(inthall),label='dPed')
    #a2.set_ylim([0,120])
    #a2.set_ylim([0,1])
    a2.legend(ncol=2, loc=0)
    a2.set_ylabel('Pedersen\n Conductance\n[S]')

    satplottools.draw_dialplot(a22)
    x, y = satplottools.latlt2cart(mlats, mlts, 'N')
    a22.plot(x, y, 'k.')
    a22.text(x[-1], y[-1], 'End')

    #Plot Hall Conductance
    a3.plot(uts, inthall, 'r.-', label='DMSP+GLOW')
    a3.plot(uts, cond_hall_op, 'b.-', label='OP2010+Robinson')
    a3.legend(ncol=2, loc=0)
    a3.set_ylabel('Hall\n Conductance\n[S]')

    #Draw conductivity as a pcolor plot with log-scaled color scale
    T, Z = np.meshgrid(uts, z)
    mappable = a4.pcolor(T,
                         Z,
                         ped.T,
                         norm=LogNorm(vmin=np.nanmin(ped),