Example #1
0
def plot_deterministic_roc_curves(roc_eval_details, tag):
    fig, axes = plt.subplots(nrows=2, ncols=3, figsize=(12, 8), dpi=180)
    fig.subplots_adjust(wspace=0.5, hspace=0.5)
    splot.style("spacepy")
    lw = 2
    I = 0
    for gname in roc_eval_details.keys():
        i, j = int(I / 3), int(np.mod(I, 3))
        ax = axes[i, j]
        clf_type = roc_eval_details[gname]
        for name in clf_type.keys():
            roc = roc_eval_details[gname][name]
            ax.plot(roc["fpr"],
                    roc["tpr"],
                    color=roc["c"],
                    lw=lw,
                    label="%s:AUC = %0.2f" % (name, roc["roc_auc"]))
            pass
        ax.plot([0, 1], [0, 1], color="navy", lw=lw, linestyle="--")
        ax.set_xlim([0.0, 1.0])
        ax.set_ylim([0.0, 1.0])
        ax.set_title(gname)
        ax.set_xlabel("False Positive Rate")
        ax.set_ylabel("True Positive Rate")
        ax.legend(loc="lower right", prop={"size": 6})
        I = I + 1
        pass
    fig.savefig("out/deterministinc_forecast_models_roc_curves_%s.png" % tag,
                bbox_inches="tight")
    return
Example #2
0
def get_stats(model, trw):
    fname = "out/det.%s.pred.%d.csv" % (model, trw)
    fname = "out/det.%s.pred.%d.g.csv" % (model, trw)
    print(fname)
    _o = pd.read_csv(fname)
    _o = _o[(_o.prob_clsf != -1.) & (_o.y_pred != -1.) & (_o.y_pred >= 0) &
            (_o.y_pred <= 9.)]
    y_pred = _o.y_pred.tolist()
    y_obs = _o.y_obs.tolist()
    _eval_details = run_validation(y_pred, y_obs, "[1995-2016]", model)
    print _eval_details
    splot.style("spacepy")
    fig, ax = plt.subplots(nrows=1, ncols=1, figsize=(6, 6))
    ax.plot(y_pred, y_obs, "k.")
    print("Updated")
    strx = "RMSE=%.2f\nr=%.2f" % (_eval_details["RMSE"], _eval_details["r"])
    ax.text(0.2,
            0.95,
            strx,
            horizontalalignment='center',
            verticalalignment='center',
            transform=ax.transAxes)
    ax.set_xlabel(r"$K_{P_{pred}}$")
    ax.set_xlim(0, 9)
    ax.set_ylim(0, 9)
    ax.set_ylabel(r"$K_{P_{obs}}$")
    fig.savefig("out/stat/det.%s.pred.%d.png" % (model, trw))
    return
Example #3
0
def plot_pred(model, trw):
    fname = "out/det.%s.pred.%d.csv" % (model, trw)
    matplotlib.rcParams['xtick.labelsize'] = 10
    print(fname)
    _o = pd.read_csv(fname)
    _o.dn = pd.to_datetime(_o.dn)
    _o = _o[(_o.prob_clsf != -1.) & (_o.y_pred != -1.) & (_o.y_pred >= 0) &
            (_o.y_pred <= 9.)]
    _o = _o[(_o.dn >= dt.datetime(2004, 7, 1))
            & (_o.dn <= dt.datetime(2004, 8, 28))]
    _o = _o.drop_duplicates(subset=["dn"])
    y_pred = np.array(_o.y_pred.tolist())
    y_obs = np.array(_o.y_obs.tolist())
    sigma = 3 * np.abs(np.array(_o.y_pred) - np.array(_o.lb))
    splot.style("spacepy")
    fig, ax = plt.subplots(nrows=1, ncols=1, figsize=(10, 6))
    fmt = matplotlib.dates.DateFormatter("%m-%d")
    ax.xaxis.set_major_formatter(fmt)
    ax.plot(_o.dn,
            y_obs,
            "ro",
            markersize=5,
            label=r"$K_{P_{obs}}$",
            alpha=0.6)
    ax.plot(_o.dn, y_pred, "bo", markersize=3, label=r"$K_{P_{pred}}$")
    ax.fill(np.concatenate([_o.dn.tolist(),
                            _o.dn.tolist()[::-1]]),
            np.concatenate(
                [y_pred - 1.9600 * sigma, (y_pred + 1.9600 * sigma)[::-1]]),
            alpha=.4,
            fc='b',
            ec='None',
            label='95% confidence interval')
    ax.fill(np.concatenate([_o.dn.tolist(),
                            _o.dn.tolist()[::-1]]),
            np.concatenate(
                [y_pred - 0.684 * sigma, (y_pred + 0.684 * sigma)[::-1]]),
            alpha=.7,
            fc='b',
            ec='None',
            label='50% confidence interval')
    ax.set_ylabel(r"$K_{P_{pred}}$")
    ax.set_xlabel(r"$UT$")
    ax.legend(loc="upper left")
    ax.tick_params(axis="both", which="major", labelsize="15")
    ax.set_xlim(dt.datetime(2004, 7, 1), dt.datetime(2004, 8, 28))
    fig.savefig("out/stat/det.pred.%s.%d.line.png" % (model, trw),
                bbox_inches="tight")
    return
Example #4
0
def run_for_TSS(model, trw):
    fdummy = "out/det.dummy.pred.%d.csv" % (trw)
    fname = "out/det.%s.pred.%d.csv" % (model, trw)
    _od = pd.read_csv(fdummy)
    _o = pd.read_csv(fname)
    _od = _od[(_od.prob_clsf != -1.) & (_od.y_pred != -1.) & (_od.y_pred >= 0)
              & (_od.y_pred <= 9.)]
    _o = _o[(_o.prob_clsf != -1.) & (_o.y_pred != -1.) & (_o.y_pred >= 0) &
            (_o.y_pred <= 9.)]
    _od.dn = pd.to_datetime(_od.dn)
    _o.dn = pd.to_datetime(_o.dn)

    stime = dt.datetime(1995, 2, 1)
    etime = dt.datetime(2016, 9, 20)
    d = stime
    skill = []
    t = []
    while (d < etime):
        try:
            t.append(d)
            dn = d + dt.timedelta(days=27)
            dum = _od[(_od.dn >= d) & (_od.dn < dn)]
            mod = _o[(_o.dn >= d) & (_o.dn < dn)]
            rmse_dum = verify.RMSE(dum.y_pred, dum.y_obs)
            rmse = verify.RMSE(mod.y_pred, mod.y_obs)
            print(d, rmse, rmse_dum, verify.skill(rmse, rmse_dum))
            skill.append(verify.skill(rmse, rmse_dum))
            d = d + dt.timedelta(days=1)
        except:
            pass
        pass
    skill = np.array(skill)
    #skill = nan_helper(skill)
    fmt = matplotlib.dates.DateFormatter("%d %b\n%Y")
    splot.style("spacepy")
    fig, ax = plt.subplots(nrows=1, ncols=1, figsize=(10, 6))
    ax.xaxis.set_major_formatter(fmt)
    ax.plot(t, skill, "k.", label="")
    #ax.plot(t,smooth(np.array(skill),101),"r.")
    #strx = "RMSE:%.2f\nr:%.2f"%(_eval_details["RMSE"],_eval_details["r"])
    #ax.text(0.2,0.8,strx,horizontalalignment='center',verticalalignment='center', transform=ax.transAxes)
    ax.set_ylabel(r"$TSS(\%)$")
    ax.set_xlabel(r"$Time$")
    ax.set_xlim(dt.datetime(1995, 1, 1), dt.datetime(2017, 1, 1))
    ax.set_ylim(0, 100)
    fig.savefig("out/stat/det.%s.tss.%d.png" % (model, trw))
Example #5
0
    def plotSummary(self, timerange=None, coord_sys=None, fig_target=None, spec=False, orbit_params=(False, True),
                    **kwargs):
        """Generate summary plot of AE9/AP9/SPM data loaded
        
        spec : if True, plot spectrogram instead of flux/fluence lineplot, requires 'ecol' keyword
        """
        if timerange:
            if isinstance(timerange, spt.Ticktock):
                t1 = timerange.UTC[0]
                t2 = timerange.UTC[-1]
            elif isinstance(timerange[0], dt.datetime):
                t1 = timerange[0]
                t2 = timerange[-1]
            else:
                raise TypeError('Incorrect data type provided for timerange')
            # now select subset
            i_use = tb.tOverlapHalf([t1, t2], self['Epoch'])
            t_use = self['Epoch'][i_use]
            c_use = self['Coords'][i_use]
            f_use = self[self.attrs['varname']][i_use, ...]
        else:
            t_use = self['Epoch']
            c_use = self['Coords']
            f_use = self[self.attrs['varname']]

        if coord_sys and (coord_sys.upper() != c_use.attrs['COORD_SYS']):
            # TODO: We assume cartesian, make flexible so can take spherical
            cx = spc.Coords(c_use, c_use.attrs['COORD_SYS'], 'car')
            cx.ticks = spt.Ticktock(t_use)
            cx = cx.convert(coord_sys.upper(), 'car').data
        else:
            coord_sys = c_use.attrs['COORD_SYS']
            cx = c_use
        sys_subs = r'$_{' + coord_sys + r'}$'

        splot.style('spacepy')
        if orbit_params[0]:
            landscape = orbit_params[1]
            locs = [121, 122] if landscape else [211, 212]
        else:
            locs = [223, 224]
            landscape = True
        if fig_target:
            fig, ax1 = splot.set_target(fig_target, loc=locs[0])
        else:
            fig, ax1 = splot.set_target(fig_target, figsize=(8, 8), loc=locs[0])
        fig, ax2 = splot.set_target(fig, loc=locs[1])

        ax1 = self._makeOrbitAxis(cx[:, 0], cx[:, 1], ax1)
        ax2 = self._makeOrbitAxis(cx[:, 0], cx[:, 2], ax2)
        if landscape: ax1.set_xlabel('X{0} [{1}]'.format(sys_subs, self['Coords'].attrs['UNITS']))
        ax2.set_xlabel('X{0} [{1}]'.format(sys_subs, self['Coords'].attrs['UNITS']))
        ax1.set_ylabel('Y{0} [{1}]'.format(sys_subs, self['Coords'].attrs['UNITS']))
        ax2.set_ylabel('Z{0} [{1}]'.format(sys_subs, self['Coords'].attrs['UNITS']))
        ax1xl, ax1yl, ax2xl, ax2yl = ax1.get_xlim(), ax1.get_ylim(), ax2.get_xlim(), ax2.get_ylim()
        maxabslim = np.max(np.abs([ax1xl, ax1yl, ax2xl, ax2yl]))
        if np.abs((ax1.get_xlim()[1] - ax1.get_xlim()[0])) < 1:
            refpt = maxabslim
            ax1.set_xlim([-1.25 * refpt, 1.25 * refpt])
            ax1.set_ylim(ax1.get_xlim())
            refpt = ax2.get_xlim()[0]
            ax2.set_xlim([-1.25 * refpt, 1.25 * refpt])
            ax2.set_ylim(ax1.get_xlim())
        else:
            ax1.set_xlim([-maxabslim, maxabslim])
            ax1.set_ylim([-maxabslim, maxabslim])
            ax2.set_xlim([-maxabslim, maxabslim])
        ax2.set_ylim(ax2.get_xlim())
        ax1.invert_yaxis()
        ax1.invert_xaxis()
        ax2.invert_xaxis()
        ax1.set_aspect('equal')
        ax2.set_aspect('equal')

        if not orbit_params[0]:
            ax3 = splot.plt.subplot2grid((2, 2), (0, 0), colspan=2)
            if not spec:
                l3 = ax3.semilogy(t_use, f_use)
                ylab = '{0} ['.format(self.attrs['varname']) + re.sub('(\^[\d|-]*)+', _grp2mathmode,
                                                                      self[self.attrs['varname']].attrs['UNITS']) + ']'
                ax3.set_ylabel(ylab)
                for ll, nn in zip(l3, self['Energy']):
                    ll.set_label('{0} {1}'.format(nn, self['Energy'].attrs['UNITS']))
                ncol = len(self['Energy']) // 2 if len(self['Energy']) <= 6 else 3
                leg = ax3.legend(loc='center', bbox_to_anchor=(0.5, 1), ncol=ncol,
                                 frameon=True, framealpha=0.5)
                lims3 = ax3.get_ylim()
                newupper = 10 ** (np.log10(lims3[0]) + (np.log10(lims3[1] / lims3[0]) * 1.125))
                ax3.set_ylim([lims3[0], newupper])
                splot.applySmartTimeTicks(ax3, t_use)
                fig.tight_layout()
                pos3 = ax3.get_position()
                ax3.set_position([pos3.x0, pos3.y0, pos3.width, pos3.height * 0.8])
                # fig.suptitle('{model_type}\n'.format(**self.attrs) +
                #             '{0} - {1}'.format(t_use[0].isoformat()[:19], t_use[-1].isoformat()[:19]))
            else:
                if timerange: raise NotImplementedError('Time range selection not yet implemented for spectrograms')
                pos3 = ax3.get_position()
                ax3.set_position([pos3.x0, pos3.y0, pos3.width, pos3.height * 0.9])
                ecol = kwargs['ecol'] if 'ecol' in kwargs else 0
                ax3 = self.plotSpectrogram(target=ax3, ecol=ecol)
                splot.plt.subplots_adjust(wspace=0.3)
                pos1 = ax1.get_position()
                ax1.set_position([pos3.x0, pos1.y0, pos1.width, pos1.height])

        splot.revert_style()
        return fig
Example #6
0
import datetime as dt
import numpy as np
from scipy import linalg
from scipy.signal import decimate
import matplotlib.pyplot as plt
import spacepy.toolbox as tb
import spacepy.plot as splot
import spacepy.pybats.bats
import supermag_parser
splot.style('default')
try:
    assert origdata
except:
    origdata = spacepy.pybats.bats.MagFile('magnetometers_e20000812-010000.mag')
    origdata.calc_h()
    origdata.calc_dbdt()

smdata = supermag_parser.supermag_parser('supermag-20000810-20000812.txt')

stations = ['YKC', 'MEA', 'NEW', 'FRN', 'IQA', 'PBQ', 'OTT', 'FRD', 'VIC']
stations = [key for key in origdata.keys() if len(key)==3]

for stat in stations:
    if stat not in smdata.station: continue
    subset = origdata[stat]
    simtime = subset['time'][::6]
    dBdte = decimate(subset['dBdte'], 6)
    dBdtn = decimate(subset['dBdtn'], 6)
    dBdth = np.array([linalg.norm([dBdtn[i], dBdte[i]]) for i in range(len(dBdtn))])
    smstat = smdata.station[stat]
    Bdoth = np.array([linalg.norm(smstat['Bdot'][i,:2]) for i in range(len(smstat['Bdot']))])
Example #7
0
def proba_storm_forcast(model, trw):
    import matplotlib.gridspec as gridspec
    spec = gridspec.GridSpec(ncols=1, nrows=10)
    fname = "out/det.%s.pred.%d.csv" % (model, trw)
    matplotlib.rcParams['xtick.labelsize'] = 10
    print(fname)
    _o = pd.read_csv(fname)
    _o.dn = pd.to_datetime(_o.dn)
    _o = _o[(_o.prob_clsf != -1.) & (_o.y_pred != -1.) & (_o.y_pred >= 0) &
            (_o.y_pred <= 9.)]
    _o = _o[(_o.dn >= dt.datetime(2004, 7, 22))
            & (_o.dn <= dt.datetime(2004, 7, 28))]
    _o = _o.drop_duplicates(subset=["dn"])
    y_pred = np.array(_o.y_pred.tolist())
    y_obs = np.array(_o.y_obs.tolist())
    sigma = 3 * np.abs(np.array(_o.y_pred) - np.array(_o.lb))
    splot.style("spacepy")
    fig = plt.figure(figsize=(10, 6))
    fig.subplots_adjust(hspace=0.5)
    #fig, ax = plt.subplots(nrows=1,ncols=1,figsize=(10,6))
    ax0 = fig.add_subplot(spec[0:2, 0])
    ax0.set_ylim(0, 9)
    ax0.set_yticks([0, 3, 6, 9])
    ax0.set_xticks([])
    ax0.set_xticklabels([])
    ax0.set_xlim(dt.datetime(2004, 7, 21, 21), dt.datetime(2004, 7, 28, 3))

    ax = fig.add_subplot(spec[2:, 0])
    fmt = matplotlib.dates.DateFormatter("%m-%d")
    ax.xaxis.set_major_formatter(fmt)
    ax.plot(_o.dn,
            y_obs,
            "ro",
            markersize=5,
            label=r"$K_{P_{obs}}$",
            alpha=0.6)
    ax.plot(_o.dn, y_pred, "bo", markersize=3, label=r"$K_{P_{pred}}$")
    ax.fill(np.concatenate([_o.dn.tolist(),
                            _o.dn.tolist()[::-1]]),
            np.concatenate(
                [y_pred - 1.9600 * sigma, (y_pred + 1.9600 * sigma)[::-1]]),
            alpha=.4,
            fc='b',
            ec='None',
            label='95% confidence interval')
    ax.fill(np.concatenate([_o.dn.tolist(),
                            _o.dn.tolist()[::-1]]),
            np.concatenate(
                [y_pred - 0.684 * sigma, (y_pred + 0.684 * sigma)[::-1]]),
            alpha=.7,
            fc='b',
            ec='None',
            label='50% confidence interval')
    ax.plot(_o.dn,
            4.5 * np.ones(len(_o)),
            "k-.",
            markersize=3,
            label=r"$K_{P_{G_0}}$")
    ax.set_ylabel(r"$K_{P_{pred}}$")
    ax.set_xlabel(r"$UT$")
    #ax.legend(loc="upper left")
    ax.tick_params(axis="both", which="major", labelsize="15")
    ax.set_xlim(dt.datetime(2004, 7, 21, 21), dt.datetime(2004, 7, 28, 3))
    cmap = matplotlib.cm.get_cmap('Spectral')
    for m, s, d in zip(y_pred, sigma, _o.dn.tolist()):
        pr = np.round((1 - norm.cdf(4.5, m, s)) * 100, 1)
        c = "g"
        if pr > 30.: c = "orange"
        if pr > 60.: c = "red"
        if pr > 30.: ax.text(d, 12.5, str(pr) + "%", rotation=90)
        markerline, stemlines, baseline = ax0.stem([d], [m], c)
        ax0.plot([d], [m], c, marker="o", markersize=6)
        #plt.setp(stemlines, 'color', cmap(pr/100.))
        plt.setp(stemlines, 'linewidth', 3.5)
        pass
    ax.set_ylim(-2, 15)
    fig.savefig("out/stat/det.pred.%s.%d.forecast.png" % (model, trw),
                bbox_inches="tight")
    return
Example #8
0
import os
import matplotlib
matplotlib.use("Agg")
import numpy as np
import spacepy.plot as splot
import matplotlib.pyplot as plt
from scipy.interpolate import interp1d
from scipy import array
from scipy.stats import linregress

import statsmodels.api as sm
from statsmodels.formula.api import ols
import pandas as pd

splot.style("spacepy_altgrid")
fontT = {"family": "serif", "color": "k", "weight": "normal", "size": 8}
font = {"family": "serif", "color": "black", "weight": "normal", "size": 10}

from matplotlib import font_manager
ticks_font = font_manager.FontProperties(family="serif",
                                         size=10,
                                         weight="normal")
matplotlib.rcParams["xtick.color"] = "k"
matplotlib.rcParams["ytick.color"] = "k"
matplotlib.rcParams["xtick.labelsize"] = 10
matplotlib.rcParams["ytick.labelsize"] = 10
matplotlib.rcParams["mathtext.default"] = "default"

c = 3e8  #m/s
w = 2 * np.pi * 30e6  #rad/s
me = 9.31e-31  #kg
Example #9
0
import spacepy
import spacepy.pybats.bats as bts
import sys
sys.path.append('/Users/sgraf/Desktop/SWMFtools')
sys.path.append('/Users/sgraf/Desktop/SWMFtools/dBdt')
import util
import matplotlib.pyplot as plt
import matplotlib
import supermag_parser

import spacepy.plot as splot
splot.style('spacepy')
plt.rcParams["legend.frameon"] = True
plt.rcParams["legend.facecolor"] = 'white'


def results_summary_update(log, geolog, show=True):
    """3-panel summary plot from log and geoindex files
    """
    fig, axes = plt.subplots(figsize=(10, 10),
                             nrows=3,
                             ncols=1,
                             sharex=True,
                             gridspec_kw={'height_ratios': [2, 2, 1]})
    geolog.add_ae_quicklook(val='AU',
                            plot_obs=True,
                            target=axes[0],
                            label='Unsmoothed',
                            c='r')
    geolog.add_ae_quicklook(val='AL',
                            plot_obs=True,
Example #10
0
                 validation_split=0.1,
                 verbose=1)

#print y
#score, acc = model.evaluate(X, y, batch_size=1)
#print('Test score:', score)
#print('Test accuracy:', acc)

y_pred_keras = model.predict(X).ravel()
print y_pred_keras
fpr_keras, tpr_keras, thresholds_keras = roc_curve(y, y_pred_keras)
auc_keras = auc(fpr_keras, tpr_keras)
print auc_keras
xx = True
if xx:
    splot.style("spacepy")
    plt.figure(1)
    plt.plot([0, 1], [0, 1], 'k--')
    plt.plot(fpr_keras,
             tpr_keras,
             label='Keras (area = {:.3f})'.format(auc_keras))
    #plt.plot(fpr_rf, tpr_rf, label='RF (area = {:.3f})'.format(auc_rf))
    plt.xlabel('False positive rate')
    plt.ylabel('True positive rate')
    plt.title('ROC curve')
    plt.legend(loc='best')
    plt.xlim(0, 1)
    plt.ylim(0, 1)
    #plt.show()
    plt.savefig("out/stat/keras.roc.png")
Example #11
0
    def plotSummary(self,
                    timerange=None,
                    coord_sys=None,
                    fig_target=None,
                    spec=False,
                    orbit_params=(False, True),
                    **kwargs):
        """Generate summary plot of AE9/AP9/SPM data loaded
        
        spec : if True, plot spectrogram instead of flux/fluence lineplot, requires 'ecol' keyword
        """
        if timerange:
            if isinstance(timerange, spt.Ticktock):
                t1 = timerange.UTC[0]
                t2 = timerange.UTC[-1]
            elif isinstance(timerange[0], dt.datetime):
                t1 = timerange[0]
                t2 = timerange[-1]
            else:
                raise TypeError('Incorrect data type provided for timerange')
            # now select subset
            i_use = tb.tOverlapHalf([t1, t2], self['Epoch'])
            t_use = self['Epoch'][i_use]
            c_use = self['Coords'][i_use]
            f_use = self[self.attrs['varname']][i_use, ...]
        else:
            t_use = self['Epoch']
            c_use = self['Coords']
            f_use = self[self.attrs['varname']]

        if coord_sys and (coord_sys.upper() != c_use.attrs['COORD_SYS']):
            # TODO: We assume cartesian, make flexible so can take spherical
            cx = spc.Coords(c_use, c_use.attrs['COORD_SYS'], 'car')
            cx.ticks = spt.Ticktock(t_use)
            cx = cx.convert(coord_sys.upper(), 'car').data
        else:
            coord_sys = c_use.attrs['COORD_SYS']
            cx = c_use
        sys_subs = r'$_{' + coord_sys + r'}$'

        splot.style('spacepy')
        if orbit_params[0]:
            landscape = orbit_params[1]
            locs = [121, 122] if landscape else [211, 212]
        else:
            locs = [223, 224]
            landscape = True
        if fig_target:
            fig, ax1 = splot.set_target(fig_target, loc=locs[0])
        else:
            fig, ax1 = splot.set_target(fig_target,
                                        figsize=(8, 8),
                                        loc=locs[0])
        fig, ax2 = splot.set_target(fig, loc=locs[1])

        ax1 = self._makeOrbitAxis(cx[:, 0], cx[:, 1], ax1)
        ax2 = self._makeOrbitAxis(cx[:, 0], cx[:, 2], ax2)
        if landscape:
            ax1.set_xlabel('X{0} [{1}]'.format(sys_subs,
                                               self['Coords'].attrs['UNITS']))
        ax2.set_xlabel('X{0} [{1}]'.format(sys_subs,
                                           self['Coords'].attrs['UNITS']))
        ax1.set_ylabel('Y{0} [{1}]'.format(sys_subs,
                                           self['Coords'].attrs['UNITS']))
        ax2.set_ylabel('Z{0} [{1}]'.format(sys_subs,
                                           self['Coords'].attrs['UNITS']))
        ax1xl, ax1yl, ax2xl, ax2yl = ax1.get_xlim(), ax1.get_ylim(
        ), ax2.get_xlim(), ax2.get_ylim()
        maxabslim = np.max(np.abs([ax1xl, ax1yl, ax2xl, ax2yl]))
        if np.abs((ax1.get_xlim()[1] - ax1.get_xlim()[0])) < 1:
            refpt = maxabslim
            ax1.set_xlim([-1.25 * refpt, 1.25 * refpt])
            ax1.set_ylim(ax1.get_xlim())
            refpt = ax2.get_xlim()[0]
            ax2.set_xlim([-1.25 * refpt, 1.25 * refpt])
            ax2.set_ylim(ax1.get_xlim())
        else:
            ax1.set_xlim([-maxabslim, maxabslim])
            ax1.set_ylim([-maxabslim, maxabslim])
            ax2.set_xlim([-maxabslim, maxabslim])
        ax2.set_ylim(ax2.get_xlim())
        ax1.invert_yaxis()
        ax1.invert_xaxis()
        ax2.invert_xaxis()
        ax1.set_aspect('equal')
        ax2.set_aspect('equal')

        if not orbit_params[0]:
            ax3 = splot.plt.subplot2grid((2, 2), (0, 0), colspan=2)
            if not spec:
                l3 = ax3.semilogy(t_use, f_use)
                ylab = '{0} ['.format(self.attrs['varname']) + re.sub(
                    '(\^[\d|-]*)+', _grp2mathmode,
                    self[self.attrs['varname']].attrs['UNITS']) + ']'
                ax3.set_ylabel(ylab)
                for ll, nn in zip(l3, self['Energy']):
                    ll.set_label('{0} {1}'.format(
                        nn, self['Energy'].attrs['UNITS']))
                ncol = len(self['Energy']) // 2 if len(
                    self['Energy']) <= 6 else 3
                leg = ax3.legend(loc='center',
                                 bbox_to_anchor=(0.5, 1),
                                 ncol=ncol,
                                 frameon=True,
                                 framealpha=0.5)
                lims3 = ax3.get_ylim()
                newupper = 10**(np.log10(lims3[0]) +
                                (np.log10(lims3[1] / lims3[0]) * 1.125))
                ax3.set_ylim([lims3[0], newupper])
                splot.applySmartTimeTicks(ax3, t_use)
                fig.tight_layout()
                pos3 = ax3.get_position()
                ax3.set_position(
                    [pos3.x0, pos3.y0, pos3.width, pos3.height * 0.8])
                # fig.suptitle('{model_type}\n'.format(**self.attrs) +
                #             '{0} - {1}'.format(t_use[0].isoformat()[:19], t_use[-1].isoformat()[:19]))
            else:
                if timerange:
                    raise NotImplementedError(
                        'Time range selection not yet implemented for spectrograms'
                    )
                pos3 = ax3.get_position()
                ax3.set_position(
                    [pos3.x0, pos3.y0, pos3.width, pos3.height * 0.9])
                ecol = kwargs['ecol'] if 'ecol' in kwargs else 0
                ax3 = self.plotSpectrogram(target=ax3, ecol=ecol)
                splot.plt.subplots_adjust(wspace=0.3)
                pos1 = ax1.get_position()
                ax1.set_position([pos3.x0, pos1.y0, pos1.width, pos1.height])

        splot.revert_style()
        return fig
    print('\t<<<OPERATING IN DEBUG MODE!>>>')
else:
    matplotlib.rcParams['figure.max_open_warning'] = 1E6
    matplotlib.use('Agg')

import numpy as np

import matplotlib.pyplot as plt
from matplotlib.dates import date2num

import spacepy.pybats as pb
import spacepy.pybats.bats as pbs
from spacepy.plot import applySmartTimeTicks, style

# Update to Spacepy Style
style()


def get_start_time(prefix):
    '''
    Try to find start time in PARAM files.  Use prefix to determine
    where PARAMs should be.
    '''

    from spacepy.pybats import parse_filename_time

    starttime = False

    # Start by searching for PARAM.in files in PWD and, if necessary,
    # up one or two directories.
    params = glob('PARAM*')
Example #13
0
#!/usr/bin/python
# -*- coding: utf-8 -*-

from __future__ import division

import spacepy, matplotlib
from spacepy.toolbox import binHisto
import numpy as np
import datetime as dt
import substorm_model as msm
import matplotlib.pyplot as plt
import spacepy.plot as splot
splot.style('spacepy')

mu0 = 4e-7*np.pi

satname = 'WIND' #'ACE'
if satname=='ACE':
    acedata = spacepy.datamodel.fromHDF5('BAS_ACEdata.h5')
    acedata['time'] = spacepy.datamodel.dmarray([dt.datetime.strptime(z, '%Y-%m-%dT%H:%M:%S') for z in acedata['time']])
    vel = np.sqrt(acedata['vx']**2 + acedata['vy']**2 + acedata['vz']**2)*1e3
    b2 = acedata['bx']**2+acedata['by']**2+acedata['bz']**2
    btot = np.sqrt(b2)*1e-9
    theta = np.arctan2(acedata['by'],acedata['bz'])
    pow_in = np.sin(theta/2.)**4 * vel * btot**2
elif satname=='WIND':
    data = spacepy.datamodel.fromHDF5('Wind_NAL.h5')
    pow_in = data['input']

#delta = dt.timedelta(0,60)
#numericDelta = delta.days*86400+delta.seconds
Example #14
0
def plot_orbits(orbits, lim=[-20, 20], coord='GSM'):
    '''
    Given a list of satellite orbit objects, plot the orbit in a simple
    magnetosphere.
    '''

    import matplotlib.pyplot as plt
    from matplotlib.ticker import MultipleLocator

    from spacepy.empiricals import getMagnetopause
    from spacepy.pybats import add_planet
    from spacepy.pybats.dipole import b_line
    from spacepy.plot import style

    style()

    # Some parameters:
    ncol = 8
    top = .88 if len(orbits) < (2 * ncol + 1) else .855

    # Set up plot:
    fig = plt.figure(figsize=(11, 5))
    fig.subplots_adjust(top=top,
                        bottom=0.11,
                        left=0.09,
                        right=0.95,
                        hspace=0.2,
                        wspace=0.265)
    a1, a2 = fig.subplots(1, 2)

    for a in (a1, a2):
        add_planet(a)
        a.set_aspect('equal')
        a.set_xlim(lim)
        a.set_ylim(lim)
        a.set_xlabel(f'{coord} X ($R_E$)', size=16)
        a.xaxis.set_major_locator(MultipleLocator(10))
        a.yaxis.set_major_locator(MultipleLocator(10))
    a1.set_ylabel(f'{coord} Y ($R_E$)', size=16)
    a2.set_ylabel(f'{coord} Z ($R_E$)', size=16)

    # equatorial plane- add magpause:
    pause = getMagnetopause({'P': [1.5], 'Bz': [-2]})
    a1.plot(pause[0, :, 0], pause[0, :, 1], 'k--', alpha=.75, zorder=1)

    # meridional plane- add field lines:
    for L in [3, 6.6]:
        x, z = b_line(L, 0, 101)
        a2.plot(x, z, 'k-', alpha=.5, zorder=1)
        x, z = b_line(-L, 0, 101)
        a2.plot(x, z, 'k-', alpha=.5, zorder=1)

    # Add orbits:
    lines, labels = [], []
    for s in orbits:
        # Add lines:
        l = a1.plot(s['xyz'][0, :], s['xyz'][1, :])[0]
        l = a2.plot(s['xyz'][0, :], s['xyz'][2, :])[0]
        lines.append(l)
        labels.append(s.attrs['file'][:-4])

        # Annotate:
        for i in (0, -1):
            a1.plot(s['xyz'][0, i], s['xyz'][1, i], 'o', c=l.get_c())
            a1.annotate(f"{s['time'][i]:%Y-%m-%dT%H:%M}",
                        [s['xyz'][0, i], s['xyz'][1, i]],
                        c=l.get_c(),
                        size=8)
            a2.plot(s['xyz'][0, i], s['xyz'][2, i], 'o', c=l.get_c())
            a2.annotate(f"{s['time'][i]:%Y-%m-%dT%H:%M}",
                        [s['xyz'][0, i], s['xyz'][2, i]],
                        c=l.get_c(),
                        size=8)

    # Add legend:
    fig.legend(lines, labels, loc='upper left', fontsize=10, ncol=8)

    return fig