def plot_panel(inargs, plot_list, title_str):
    """
    
    Args:
        inargs: Command line arguments
        plot_list: List of metrics [exp_id][time, metric_dim]
        title_str: Title
    """
    if not inargs.upscale == 1:
        title_str += '_up-' + str(inargs.upscale)

    if config.metric_dict[inargs.metric.split('-')[0]]['plot_type'] == 'line':
        fig = h.plot_line(plot_list, inargs.exp_id, inargs.metric, title_str)
    elif config.metric_dict[inargs.metric.split('-')[0]]['plot_type'] == 'sal':
        fig = h.plot_sal(plot_list, inargs.exp_id, inargs.metric, title_str)
    elif config.metric_dict[inargs.metric.split('-')
                            [0]]['plot_type'] == 'hist':
        fig = h.plot_hist(plot_list, inargs.exp_id, inargs.metric, title_str,
                          inargs.hist_normalize)
    else:
        raise ValueError(
            'Plot type %s does not exist.' %
            config.metric_dict[inargs.metric.split('-')[0]]['plot_type'])
    exp_id_str = '_'.join([e for e in inargs.exp_id if not e == 'radar'])
    if not inargs.fg:
        plot_dir = config.plotdir + '/' + exp_id_str + '/fc_precipitation/'
    else:
        plot_dir = config.plotdir + '/' + exp_id_str + '/fg_precipitation/'

    plot_str = inargs.metric + '_' + title_str + '_' + inargs.radar_comp

    if inargs.combine_masks is not None:
        plot_str += '_comb-' + inargs.combine_masks

    h.save_fig_and_log(fig, plot_str, plot_dir)
Esempio n. 2
0
def plot_correlation(inargs):
    """
    Plots correlation between N and m in a scatter plot

    Parameters
    ----------
    inargs : argparse object
      Argparse object with all input arguments

    """

    # Read pre-processed data
    rootgroup = read_netcdf_dataset(inargs)

    pw = get_config(inargs, 'plotting', 'page_width')
    fig, axarr = plt.subplots(1, 2, figsize=(pw, pw / 2.5))

    mean_m = rootgroup.variables['mean_m'][:, :, 0, 0, 0]
    mean_N = rootgroup.variables['mean_N'][:, :, 0, 0, 0]

    # axarr[0].plot(rootgroup.variables['time'][:], mean_m, label='non-separated')
    # axarr[1].plot(rootgroup.variables['time'][:], mean_M, label='non-separated')
    axarr[0].scatter(mean_m, mean_N)
    print np.corrcoef(mean_m, mean_N)[0, 1]

    axarr[0].set_xlabel('m')
    axarr[0].set_ylabel('N')
    axarr[0].legend()
    # Save figure and log
    save_fig_and_log(fig, rootgroup, inargs, 'correlation', tight=True)
Esempio n. 3
0
def plot_domain_mean_timeseries_individual(inargs, plot_type):
    """
    Function to plot time series of domain mean precipitation for each day

    Parameters
    ----------
    inargs : argparse object
      Argparse object with all input arguments
    plot_type : str
      Type of plot. Must be 'precipitation' or 'cape_tauc'

    """

    assert plot_type in ['precipitation', 'cape_tauc'], \
        'Type must be precipitation or cape_tauc'

    # Read pre-processed data
    rootgroup = read_netcdf_dataset(inargs)
    n_days = rootgroup.dimensions['date'].size

    # Set up figure
    n_cols = 4
    n_rows = int(np.ceil(float(n_days) / n_cols))

    fig, axmat = plt.subplots(n_rows,
                              n_cols,
                              sharex=True,
                              sharey=True,
                              figsize=(10, 3 * n_rows))
    axflat = np.ravel(axmat)

    # Loop over axes / days
    for iday in range(n_days):
        dateobj = (timedelta(seconds=int(rootgroup.variables['date'][iday])) +
                   datetime(1, 1, 1))
        datestr = dateobj.strftime(get_config(inargs, 'plotting', 'date_fmt'))
        axflat[iday].set_title(datestr)
        if iday >= ((n_cols * n_rows) - n_cols):  # Only bottom row
            axflat[iday].set_xlabel('Time [UTC]')

        if plot_type == 'precipitaiton':
            plot_precipitation_panel(inargs, axflat, iday, rootgroup)
        if plot_type == 'cape_tauc':
            plot_cape_tauc_panel(inargs, axflat, iday, rootgroup)

    # Finish figure
    axflat[0].legend(loc=0)

    plt.tight_layout()

    # Save figure
    save_fig_and_log(fig, rootgroup, inargs, plot_type + '_ts_individual')
Esempio n. 4
0
def plot_prec_freq_hist(inargs):
    """
    Plot precipitation histogram comparing the three groups
    
    Parameters
    ----------
    inargs : argparse object
      Argparse object with all input arguments

    """

    # Read pre-processed data
    rootgroup = read_netcdf_dataset(inargs)

    # Set up figure
    fig, ax = plt.subplots(1, 1, figsize=(4, 3.5))
    x = np.arange(rootgroup.variables['prec_freq_bins'][:].shape[0])

    # Loop over groups
    for ig, group in enumerate(rootgroup.groups):
        # Compute mean in all directions but bins
        mean_hist = np.mean(rootgroup.groups[group].variables['prec_freq'][:],
                            axis=(0, 1, 3))
        ax.bar(x[1:] + ig * 0.2, mean_hist[1:], width=0.2,
               color=get_config(inargs, 'colors', group), label=group)

    # Make figure look nice
    ax.legend(loc=0, prop={'size': 10})
    plt.xticks(x[1:], rootgroup.variables['prec_freq_bins'][:-1])
    ax.set_xlabel('Hourly accumulation [mm/h]')
    ax.set_ylabel('Number of grid points')
    date_str = get_composite_str(inargs, rootgroup)
    ax.set_title(date_str, fontsize=12)

    plt.tight_layout()

    # Save figure and log
    save_fig_and_log(fig, rootgroup, inargs, 'prec_freq_hist')
Esempio n. 5
0
def plot_CC06b_fig9(inargs):
    """Plots square root of normalized variance against square root of 1/N
    
    Parameters
    ----------
    inargs : argparse object
      Argparse object with all input arguments

    """

    # Read pre-processed data
    rootgroup = read_netcdf_dataset(inargs)

    pw = get_config(inargs, 'plotting', 'page_width')
    fig, ax = plt.subplots(1, 1, figsize=(pw / 2.5, pw / 2.5))

    # [date, time, n, x, y]
    var_M = rootgroup.variables['var_M'][:, :, :, :, :]
    mean_M = rootgroup.variables['mean_M'][:, :, :, :, :]
    mean_N = rootgroup.variables['mean_N'][:, :, :, :, :]

    y_data = var_M / (mean_M**2)
    y_data = np.sqrt(np.nanmean(y_data, axis=(0, 1, 3, 4)))
    x_data = 2. / mean_N
    x_data = np.sqrt(np.nanmean(x_data, axis=(0, 1, 3, 4)))

    # axarr[0].plot(rootgroup.variables['time'][:], mean_m, label='non-separated')
    # axarr[1].plot(rootgroup.variables['time'][:], mean_M, label='non-separated')
    ax.scatter(x_data, y_data)
    ax.plot([0, 2.5], [0, 2.5], c='gray', zorder=0.1)

    ax.set_xlabel('Sqrt(2/N)')
    ax.set_ylabel('Sqrt(Var(M)/M**2)')
    ax.legend()
    # Save figure and log
    save_fig_and_log(fig, rootgroup, inargs, 'CC06b_fig9', tight=True)
Esempio n. 6
0
def plot_diurnal(inargs):
    """
    Plots the diurnal plots for three different scales.

    Parameters
    ----------
    inargs : argparse object
      Argparse object with all input arguments

    """

    # Load dataset
    rootgroup = read_netcdf_dataset(inargs)
    # The variables have dimensions [date, time, n, x[n], y[n]]

    # Set up figure
    pw = get_config(inargs, 'plotting', 'page_width')
    ratio = 1.

    if inargs.diurnal_individual_days:
        n_days = rootgroup.dimensions['date'].size
        n_cols = 4
        n_rows = int(np.ceil(float(n_days) / n_cols))

        fig, axmat = plt.subplots(n_rows,
                                  n_cols,
                                  sharex=True,
                                  sharey=True,
                                  figsize=(pw, 2.1 * n_rows))
        axflat = np.ravel(axmat)

    else:
        fig, ax = plt.subplots(1, 1, figsize=(pw / 3., pw / 3. * ratio))

    clist = [
        get_config(inargs, 'colors', 'ens'),
        get_config(inargs, 'colors', 'det'),
        get_config(inargs, 'colors', 'third')
    ]
    labellist = ['Small: ', 'Medium: ', 'Large: ']

    # Do some further calculations to get daily composite
    for i, i_n in enumerate(inargs.diurnal_scale_inds):
        n = rootgroup.variables['n'][i_n]
        nx = int(np.floor(get_config(inargs, 'domain', 'ana_irange') / n))
        ny = int(np.floor(get_config(inargs, 'domain', 'ana_jrange') / n))
        label = labellist[i] + str(int(n * 2.8)) + 'km'

        mean_M = rootgroup.variables['mean_M'][:, :, i_n, :nx, :ny]
        mean_m = rootgroup.variables['mean_m'][:, :, i_n, :nx, :ny]
        mean_N = rootgroup.variables['mean_N'][:, :, i_n, :nx, :ny]
        var_M = rootgroup.variables['var_M'][:, :, i_n, :nx, :ny]
        var_m = rootgroup.variables['var_m'][:, :, i_n, :nx, :ny]
        var_N = rootgroup.variables['var_N'][:, :, i_n, :nx, :ny]
        try:
            corr_m_N = rootgroup.variables['corr_m_N'][:, :, i_n, :nx, :ny]
        except:
            print 'hi'

        # Flatten x and y dimensions
        mean_M = mean_M.reshape(mean_M.shape[0], mean_M.shape[1],
                                mean_M.shape[2] * mean_M.shape[3])
        mean_m = mean_m.reshape(mean_m.shape[0], mean_m.shape[1],
                                mean_m.shape[2] * mean_m.shape[3])
        mean_N = mean_N.reshape(mean_N.shape[0], mean_N.shape[1],
                                mean_N.shape[2] * mean_N.shape[3])
        var_M = var_M.reshape(var_M.shape[0], var_M.shape[1],
                              var_M.shape[2] * var_M.shape[3])
        var_m = var_m.reshape(var_m.shape[0], var_m.shape[1],
                              var_m.shape[2] * var_m.shape[3])
        var_N = var_N.reshape(var_N.shape[0], var_N.shape[1],
                              var_N.shape[2] * var_N.shape[3])
        try:
            corr_m_N = corr_m_N.reshape(corr_m_N.shape[0], corr_m_N.shape[1],
                                        corr_m_N.shape[2] * corr_m_N.shape[3])
        except:
            pass
        # Array now has dimensions [date, time, points]

        if inargs.diurnal_ext_m is not None:
            mean_m = inargs.diurnal_ext_m

        # Computations
        if inargs.plot_type == 'r_v':
            data = var_M / (2. * mean_M * mean_m)
            ylabel = r'$R_V$'
            if inargs.diurnal_ext_m is not None:
                ylabel += r' with fixed $\langle m \rangle$'
        elif inargs.plot_type == 'alpha':
            data = var_N / mean_N
            ylabel = r'$\alpha$'
        elif inargs.plot_type == 'beta':
            data = var_m / (mean_m**2)
            ylabel = r'$\beta$'
        elif inargs.plot_type == 'r_v_alpha':
            data = var_M / ((1 + var_N / mean_N) * mean_M * mean_m)
            ylabel = r'$\alpha$-adjusted $R_V$'
        elif inargs.plot_type == 'r_v_beta':
            data = var_M / ((1 + var_m / (mean_m**2)) * mean_M * mean_m)
            ylabel = r'$\beta$-adjusted $R_V$'
        elif inargs.plot_type == 'r_v_alpha_beta':
            data = var_M / ((var_N / mean_N + var_m /
                             (mean_m**2)) * mean_M * mean_m)
            ylabel = r'$\alpha$ and $\beta$-adjusted $R_V$'
        elif inargs.plot_type == 'corr_m_N':
            data = corr_m_N
            ylabel = r'corr($m$, $N$)'
        elif inargs.plot_type == 'mean_m':
            data = mean_m
            ylabel = r'mean(m)'

        if inargs.diurnal_individual_days:
            for iday, date in enumerate(rootgroup.variables['date']):
                plot_individual_panel(inargs, rootgroup, i, iday, axflat,
                                      n_cols, n_rows, ylabel, data, label,
                                      clist)

        else:
            plot_composite(inargs, rootgroup, i, data, ax, label, clist,
                           ylabel)

    # Finish figure
    if inargs.diurnal_individual_days and inargs.diurnal_legend:
        axflat[0].legend(loc=4, fontsize=8)
        plt.tight_layout()
        plt.subplots_adjust(wspace=0.15, hspace=0.25)
    elif inargs.diurnal_legend:
        ax.legend(loc=2, fontsize=8)

    # Save figure and log
    save_fig_and_log(
        fig, rootgroup, inargs, inargs.plot_type + '_individual-' +
        str(inargs.diurnal_individual_days))
        # axlist = np.ravel(np.transpose(axmat))

        for i, fobj in enumerate(plotfobjlist):
            plt.sca(axlist[i])
            if i == 0:
                mask = fobj.data > 100
            else:
                mask = None
            cf, tmp = ax_contourf(axlist[i],
                                  fobj,
                                  Basemap_drawrivers=False,
                                  npars=0,
                                  nmers=0,
                                  colors=cmPrec,
                                  pllevels=levelsPrec,
                                  sp_title=titlelist[i],
                                  extend='max',
                                  mask=mask)
            if i < 0:
                cb = fig.colorbar(cf,
                                  orientation='horizontal',
                                  fraction=0.05,
                                  pad=0.0)
        plotstr = datestr + '_' + hstr
        fig.suptitle(plotstr, fontsize=18)

        plt.tight_layout(rect=[0, 0.0, 1, 0.95])
        pd = plotdir + expid_str[:-1] + '/prec_stamps/'
        if not os.path.exists(pd): os.makedirs(pd)
        save_fig_and_log(fig, 'det_stamps_' + plotstr, pd)
Esempio n. 8
0
                      label=expid)

# Finish the plots
if args.obs == 'SYNOP':
    if args.composite == 'True':
        ax.set_xlabel('Time [UTC/h]')
    else:
        ax.set_xlabel('time from ' + yyyymmddhhmmss(tstart) + ' [h]')
    ax.set_ylabel('[' + unitdict[args.var] + ']')
    ax.axhline(0, c='gray', zorder=0.1)
    ax.legend(loc=0, fontsize=6)
    ax.set_title(plotstr + '\n RMSE (solid), Spread (dashed), Bias (dotted)')
    plt.tight_layout()
    plotdir = plotdir + expid_str[:-1] + '/verif_ana/'
    if not os.path.exists(plotdir): os.makedirs(plotdir)
    save_fig_and_log(fig, plotstr, plotdir)
    plt.close('all')

if args.obs == 'TEMP':
    axarr[0].set_xlim(rmselimdict[args.var])
    axarr[0].set_ylim(0, 1000)
    axarr[0].set_xlabel(args.var + ' RMSE [' + unitdict[args.var] + ']')
    axarr[0].set_ylabel('Pressure [hPa]')
    axarr[0].set_title('RMSE (solid) / Spread (dashed) ' + args.var)
    axarr[0].invert_yaxis()
    axarr[1].plot([0, 0], [0, 1000], c='gray')
    axarr[1].set_xlim(biaslimdict[args.var])
    axarr[1].set_ylim(0, 1000)
    axarr[1].set_xlabel(args.var + ' BIAS [' + unitdict[args.var] + ']')
    axarr[1].set_ylabel('Pressure [hPa]')
    axarr[1].set_title('Bias ' + args.var)
def plot_individual(inargs):
    """
    
    Parameters
    ----------
    inargs

    Returns
    -------

    """

    # Get data
    date_dir = (get_config(inargs, 'paths', 'raw_data') + inargs.date_start +
                '/deout_ceu_pspens/')
    t = timedelta(hours=inargs.time_start)

    if inargs.ind_var == 'PREC_ACCUM':
        ncdffn = 'lfff' + ddhhmmss(t) + '.nc_30m_surf'
        fobj = getfobj_ncdf(date_dir + str(inargs.ind_ens) + '/OUTPUT/' +
                            ncdffn,
                            fieldn='PREC_ACCUM')
        cmap = None
        colors = cmPrec
        levels = levelsPrec
    elif inargs.ind_var == 'radar':
        radarpref = (get_config(inargs, 'paths', 'radar_data') +
                     get_config(inargs, 'paths', 'radar_prefx'))
        radarsufx = get_config(inargs, 'paths', 'radar_sufix')
        dtradar = timedelta(minutes=10)
        radartime = yymmddhhmm(
            yyyymmddhh_strtotime(inargs.date_start) + t - dtradar)
        radarfn = radarpref + radartime + radarsufx
        radar_fobj = getfobj_ncdf(radarfn, fieldn='pr', dwdradar=True)
        # Crop data
        l11, l12, l21, l22, l11_rad, l12_rad, l21_rad, l22_rad = \
            get_domain_limits(inargs)
        l11_diff = l11_rad - l11
        l12_diff = l12_rad - l12
        l21_diff = l21_rad - l21
        l22_diff = l22_rad - l22
        radar_fobj.data = radar_fobj.data[l11_diff:l12_diff, l21_diff:l22_diff]
        radar_fobj.lats = radar_fobj.lats[l11_diff:l12_diff, l21_diff:l22_diff]
        radar_fobj.lons = radar_fobj.lons[l11_diff:l12_diff, l21_diff:l22_diff]
        fobj = radar_fobj
    elif inargs.ind_var in ['obj_m', 'obj_prec']:
        if inargs.ind_var == 'obj_m':
            lvl = 30
            ncdffn = 'lfff' + ddhhmmss(t) + '.nc_30m'
            fobj = getfobj_ncdf(date_dir + str(inargs.ind_ens) + '/OUTPUT/' +
                                ncdffn,
                                fieldn='W',
                                levs=lvl)
            opt_field = (getfield_ncdf(
                date_dir + str(inargs.ind_ens) + '/OUTPUT/' + ncdffn,
                fieldn='QC',
                levs=lvl) + getfield_ncdf(
                    date_dir + str(inargs.ind_ens) + '/OUTPUT/' + ncdffn,
                    fieldn='QS',
                    levs=lvl) + getfield_ncdf(
                        date_dir + str(inargs.ind_ens) + '/OUTPUT/' + ncdffn,
                        fieldn='QI',
                        levs=lvl))
        else:
            ncdffn = 'lfff' + ddhhmmss(t) + '.nc_30m_surf'
            fobj = getfobj_ncdf(date_dir + str(inargs.ind_ens) + '/OUTPUT/' +
                                ncdffn,
                                fieldn='PREC_ACCUM')
            opt_field = None

        labels, size_list, sum_list = identify_clouds(fobj.data,
                                                      1.,
                                                      opt_field=opt_field,
                                                      water=True,
                                                      neighborhood=3,
                                                      opt_thresh=0)
        fobj.data = labels
        cmap = plt.cm.prism
        colors = None
        levels = None
    else:
        raise Exception('Wrong variable!')

    # Set up figure
    pw = get_config(inargs, 'plotting', 'page_width')
    width_fraction = 2. / 9.
    ratio = 1.
    fig, ax = plt.subplots(1,
                           1,
                           figsize=(pw * width_fraction,
                                    pw * width_fraction * ratio))

    cf = plot_stamp(inargs, fobj, cmPrec, levelsPrec, ax, 'PREC_ACCUM')

    if inargs.ind_colorbar:
        cb = fig.colorbar(cf, orientation='horizontal', shrink=0.6)
        cb.set_label('Accumulation [mm/h]')

    plt.subplots_adjust(left=0.05, right=0.95, bottom=0.05, top=0.95)

    save_fig_and_log(fig, None, inargs, 'prec_individual', tight=False)
Esempio n. 10
0
def plot_m_evolution(inargs):
    """
    Plots the evolution of m.

    Parameters
    ----------
    inargs : argparse object
      Argparse object with all input arguments

    """

    # Read pre-processed data
    rootgroup = read_netcdf_dataset(inargs)

    c_red = get_config(inargs, 'colors', 'third')
    c_blue = get_config(inargs, 'colors', 'ens')

    pw = get_config(inargs, 'plotting', 'page_width')
    ratio = 0.7
    fig, ax1 = plt.subplots(1, 1, figsize=(pw / 2., pw / 2. * ratio))
    ax2 = ax1.twinx()

    mean_m = np.nanmean(rootgroup.groups['ens'].variables['cld_sum_mean'][:],
                     axis=(0,2))
    mean_m_sep = np.nanmean(rootgroup.groups['ens'].
                         variables['cld_sum_sep_mean'][:],
                         axis=(0,2))

    mean_size = np.nanmean(rootgroup.groups['ens'].variables['cld_size_mean'][:],
                        axis=(0, 2))
    mean_size_sep = np.nanmean(rootgroup.groups['ens'].
                            variables['cld_size_sep_mean'][:],
                            axis=(0, 2))

    # Get mean total mass flux
    hist_data = rootgroup.groups['ens'].variables['cld_sum'][:]
    mean_hist = np.mean(hist_data, axis=(0, 3))
    mean_hist = np.sum(mean_hist, axis=1)

    hist_data_sep = rootgroup.groups['ens'].variables['cld_sum_sep'][:]
    mean_hist_sep = np.mean(hist_data_sep, axis=(0, 3))
    mean_hist_sep = np.sum(mean_hist_sep, axis=1)

    # Convert to relative frequency
    mean_M = mean_hist * mean_m
    print(mean_M)

    # Calculate weighted mean
    weighted_mean_m = np.average(mean_m, weights=mean_hist)
    weighted_mean_m_sep = np.average(mean_m_sep, weights=mean_hist_sep)

    print('Mean m = %.2e \nMean sep m = %.2e' % (weighted_mean_m,
                                                 weighted_mean_m_sep))

    ax1.plot(rootgroup.variables['time'][:], mean_m_sep, label='separated',
            linewidth=2, c=c_red)
    ax1.plot(rootgroup.variables['time'][:], mean_m, label='non-separated',
            linewidth=2, c=c_red, linestyle='--')

    ax3 = ax1.twinx()
    ax3.plot(rootgroup.variables['time'][:], mean_M,
             linewidth=2, c='gray', zorder=0.1, alpha=0.5)
    ax3.axis('off')

    ax2.plot(rootgroup.variables['time'][:], mean_size_sep, linewidth=2,
             c=c_blue)
    ax2.plot(rootgroup.variables['time'][:], mean_size, linewidth=2, c=c_blue,
             linestyle='--')

    ax1.set_xlabel('Time [UTC]')
    ax1.set_ylabel(r'$\langle m \rangle$ [kg s$^{-1}$] (red)')
    ax2.set_ylabel(r'$\langle \sigma \rangle$ [m$^{2}$] (blue)')
    ax1.legend(fontsize=8, loc=4)

    for ax in [ax1, ax2]:
        ax.set_xticks([6, 9, 12, 15, 18, 21, 24])
        ax.set_xticklabels([6, 9, 12, 15, 18, 21, 24])
        ax.spines['top'].set_visible(False)
        ax.spines['bottom'].set_position(('outward', 3))
        ax.spines['left'].set_position(('outward', 3))
        ax.spines['right'].set_position(('outward', 3))
        ax.set_xlim((6, 24))

    plt.subplots_adjust(left=0.18, right=0.82, bottom=0.2, top=0.9)

    # Save figure and log
    save_fig_and_log(fig, rootgroup, inargs, 'm_evolution')
Esempio n. 11
0
def plot_rdf_composite(inargs):
    """
    Plots the radial distribution function as panel over all days. This copies 
    some stuff from plot_domain_mean_timeseries_composite in 
    weather_time_series.py

    Parameters
    ----------
    inargs : argparse object
      Argparse object with all input arguments

    """

    # Read pre-processed data
    rootgroup = read_netcdf_dataset(inargs)

    # Set up figure
    curve_c_dict = {
        'ens': [get_config(inargs, 'colors', 'ens'),
                get_config(inargs, 'colors', 'ens_range')],
        'obs': ['darkgray', 'lightgray'],
        'det': [get_config(inargs, 'colors', 'det'),
                'lime'],
    }
    pw = get_config(inargs, 'plotting', 'page_width')
    ratio = 0.35
    fig, axarr = plt.subplots(1, 2, figsize=(pw, pw * ratio))

    axarr[0].set_ylabel('RDF')
    for ig, group in enumerate(rootgroup.groups):
        if inargs.no_det and group == 'det':
            continue
        if inargs.rdf_sep:
            array = rootgroup.groups[group].variables['rdf_sep'][:]
        else:
            array = rootgroup.groups[group].variables['rdf'][:]
        # Convert data which at this point has dimensions
        # [date, time, radius, ens mem]

        # 1st: Plot max curve
        mx = np.nanmax(np.nanmean(array, axis=(0, 3)), axis=1)
        axarr[1].plot(rootgroup.variables['time'][:], mx, label=group,
                 c=get_config(inargs, 'colors', group), linewidth=2)

        # 2nd: Plot example curves
        for it, t in enumerate(inargs.rdf_curve_times):
            rdf_curve = np.nanmean(array[:, t, :, :], axis=(0, 2))
            if ig == 2:
                leg = str(int(rootgroup.variables['time'][t])) + ' UTC'
            else:
                leg = ' '
            # Fix linestyle
            ls = '-' if it == 0 else '--'
            axarr[0].plot(rootgroup.variables['rdf_radius'][:] * 2.8, rdf_curve,
                          label=leg, c=curve_c_dict[group][0], linewidth=1.5,
                          linestyle=ls)
            axarr[1].plot([rootgroup.variables['time'][t],
                           rootgroup.variables['time'][t]],
                          [0, inargs.rdf_y_max], c='gray', zorder=0.1,
                          alpha=2. / (it + 1), linewidth=0.5)

    axarr[1].set_ylim(0, inargs.rdf_y_max)
    axarr[0].set_ylim(0, inargs.rdf_y_max)
    axarr[1].set_xlim([6, 24])
    axarr[0].set_xlim([0, rootgroup.variables['rdf_radius'][-1] * 2.8])
    axarr[1].set_xlabel('Time [UTC]')
    axarr[0].set_xlabel('Radius [km]')

    axarr[1].set_title('b) Evolution of RDF maximum')
    axarr[0].set_title('a) Full RDF for two times')

    axarr[1].legend(loc=0, fontsize=8)
    axarr[0].legend(loc=0, fontsize=8, ncol=3)

    axarr[1].set_xticks([6, 9, 12, 15, 18, 21, 24])
    axarr[1].set_xticklabels([6, 9, 12, 15, 18, 21, 24])

    axarr[0].set_xticks(np.arange(0, 100, 20))
    axarr[0].axhline(y=1, c='gray', zorder=0.1)

    axarr[0].spines['top'].set_visible(False)
    axarr[0].spines['right'].set_visible(False)
    axarr[1].spines['right'].set_visible(False)
    axarr[1].spines['left'].set_visible(False)
    axarr[1].spines['top'].set_visible(False)
    axarr[0].spines['left'].set_position(('outward', 3))
    axarr[0].spines['bottom'].set_position(('outward', 3))
    axarr[1].spines['bottom'].set_position(('outward', 3))
    axarr[1].yaxis.set_ticks([])

    # fig.suptitle('Composite ' + get_composite_str(inargs, rootgroup) +
    #              ' sep = ' + str(inargs.rdf_sep) +
    #              ' perimeter = ' + str(inargs.footprint), fontsize=6)
    plt.subplots_adjust(wspace=0.06, left=0.1, right=0.95, bottom=0.2,
                        top=0.9)

    # Save figure and log
    save_fig_and_log(fig, rootgroup, inargs, 'rdf_composite')
Esempio n. 12
0
def plot_rdf_individual(inargs):
    """
    Plots the radial distribution function as panel over all days. This copies some stuff from 
    plot_domain_mean_timeseries_individual in weather_time_series.py
    
    Parameters
    ----------
    inargs : argparse object
      Argparse object with all input arguments

    """

    # Read pre-processed data
    rootgroup = read_netcdf_dataset(inargs)
    n_days = rootgroup.dimensions['date'].size

    # Set up figure
    n_cols = 4
    n_rows = int(np.ceil(float(n_days) / n_cols))

    fig, axmat = plt.subplots(n_rows, n_cols, sharex=True, sharey=True,
                              figsize=(get_config(inargs, 'plotting',
                                                  'page_width'),
                                       2.1 * n_rows))
    axflat = np.ravel(axmat)

    # Loop over axes / days
    for iday in range(n_days):
        ax = axflat[iday]
        dateobj = (timedelta(seconds=int(rootgroup.variables['date'][iday])) +
                   datetime(1, 1, 1))
        datestr = dateobj.strftime(get_config(inargs, 'plotting', 'date_fmt'))
        ax.text(0.35, 0.9, datestr, fontsize=10,
                transform = ax.transAxes)
        if iday >= ((n_cols * n_rows) - n_cols):  # Only bottom row
            ax.set_xlabel('Time [UTC]')
            ax.set_xticks([0, 6, 12, 18, 24])
        if iday % 4 == 0:  # Only left column
            ax.set_ylabel(r'RDF')

        for ig, group in enumerate(rootgroup.groups):

            # Get data
            if inargs.rdf_sep:
                rdf_data = rootgroup.groups[group].variables['rdf_sep'][iday]
            else:
                rdf_data = rootgroup.groups[group].variables['rdf'][iday]
            # Convert data which at this point has dimensions
            # [time, radius, ens mem]

            # Mean over ensemble dimension
            rdf = np.nanmax(np.nanmean(rdf_data, axis=2), axis=1)

            # Plot data
            ax.plot(rootgroup.variables['time'][:], rdf, label=group,
                    c=get_config(inargs, 'colors', group))

            ax.set_ylim(0, 35)
            ax.set_xlim(6, 24)
            ax.spines['top'].set_visible(False)
            ax.spines['right'].set_visible(False)
            # ax.spines['left'].set_position(('outward', 3))
            ax.spines['bottom'].set_position(('outward', 3))

    # Finish figure
    axflat[0].legend(loc=3)
    plt.subplots_adjust(wspace=0.15, hspace=0.25)
    plt.tight_layout()

    # Save figure and log
    save_fig_and_log(fig, rootgroup, inargs, 'rdf_individual')
Esempio n. 13
0
def plot_cloud_size_hist(inargs):
    """
    Plot histograms of cloud size and precipitation
    
    Parameters
    ----------
    inargs : argparse object
      Argparse object with all input arguments

    """

    # Read pre-processed data
    rootgroup = read_netcdf_dataset(inargs)

    # Set up figure
    pw = get_config(inargs, 'plotting', 'page_width')
    c_red = get_config(inargs, 'colors', 'third')
    ratio = 0.7
    fig, ax = plt.subplots(1, 1, figsize=(pw / 2., pw / 2. * ratio))

    # Convert data for plotting
    var = 'cld_'
    if inargs.size_hist_sum:
        var += 'sum'
    else:
        var += 'size'
    if inargs.size_hist_sep:
        var += '_sep'
    right_edges = rootgroup.variables[var + '_bins'][:]
    x = right_edges - np.diff(right_edges)[0] / 2
    bin_width = np.diff(right_edges)[0]
    print('Bin width = %.2e' % (bin_width))

    # Loop over groups
    for ig, group in enumerate(rootgroup.groups):
        if inargs.no_det and group == 'det':
            continue
        if inargs.no_obs and group == 'obs':
            continue
        # Load data
        hist_data = rootgroup.groups[group].variables[var][:]
        print(np.sum(hist_data))

        if inargs.size_hist_y_type == 'relative_frequency':
            mean_hist = np.mean(hist_data, axis=(0, 1, 3))

            # Convert to relative frequency
            mean_hr_no_cld = np.sum(mean_hist)  # Mean hourly cloud sum

            plot_data = mean_hist / mean_hr_no_cld
        elif inargs.size_hist_y_type == 'mean_number':
            plot_data = np.mean(hist_data, axis=(0, 1, 3))
            mean_hr_no_cld = np.sum(plot_data)
        elif inargs.size_hist_y_type == 'total_number':
            plot_data = np.mean(hist_data, axis=3)
            plot_data = np.sum(plot_data, axis=(0, 1))
        else:
            raise Exception('size_hist_y_type wrong!')

        # Fit curves only for ens
        if group == 'ens':
            print('Actual N = %.2e' % (mean_hr_no_cld))

            # Exponential
            a, b = fit_curve(x, plot_data, fit_type='exp')
            print('Exp fit params: a = %.2e; b = %.2e' % (a, b))
            print('Exp fit m = %.2e' % (b ** -1))
            print('Exp fit N = %.2e' % (1 / b / bin_width * np.exp(a)))
            ax.plot(x, np.exp(a - b * x), c=c_red, label='Exponential',
                    zorder=0.1)
            # Power law
            a, b = fit_curve(x, plot_data, fit_type='pow')
            # print('Pow-law fit params: a = %.2e; b = %.2e' % (a, b))
            ax.plot(x, np.exp(a-b*np.log(x)), c='darkorange', label='Power-law',
                    zorder=0.1)


        # Plot on log-linear
        # ax.plot(x, plot_data, color=get_config(inargs, 'colors', group),
        #         label=group, linewidth=2)
        # ax.scatter(x, plot_data, color=get_config(inargs, 'colors', group),
        #            label=group, s=15, linewidth=0.5, edgecolor='k')
        ax.scatter(x, plot_data, color=get_config(inargs, 'colors', group),
                   s=15, linewidth=0.3, edgecolor='k', label=group, alpha=0.7)
        ax.set_yscale('log')
        # ax.set_title(var)

        if inargs.size_hist_sum:
            xlabel = 'Cloud sum [???]'
            if inargs.var == 'm':
                xlabel = r'Cloud mass flux [kg s$^{-1}$]'
        else:
            xlabel = r'Cloud size [m$^2$]'

        ax.set_xlabel(xlabel)
        if inargs.size_hist_log:
            ax.set_xscale('log')

        if inargs.size_hist_y_type == 'relative_frequency':
            ylabel = 'Relative frequency'
            #ax.set_ylim(5e-5, 1e0)
        else:
            ylabel = inargs.size_hist_y_type

    ax.spines['top'].set_visible(False)
    ax.spines['right'].set_visible(False)
    ax.spines['left'].set_position(('outward', 3))
    ax.spines['bottom'].set_position(('outward', 3))
    #ax.yaxis.set_ticklabels([])
    ax.set_ylim([0.6e-6, 1])
    ax.set_xlim([0, x[-1]])
    plt.yticks(rotation=90)

    ax.set_ylabel(ylabel)
    ax.legend(loc=0, fontsize=8)
    title = r'a) Separated $\langle m \rangle$' if inargs.size_hist_sep \
        else r'b) Non-separated $\langle m \rangle$'
    ax.set_title(title)
    plt.subplots_adjust(left=0.15, right=0.93, bottom=0.2, top=0.9)

    # Save figure and log
    save_fig_and_log(fig, rootgroup, inargs, 'size_hist')
Esempio n. 14
0
def plot_prec_stamps(inargs):
    """
    Plots precipitation stamps of obs, det and ensemble every hour for each
    date and time specified
    
    Parameters
    ----------
    inargs : argparse object
      Argparse object with all input arguments

    """

    # TODO: Update colors
    cmPrec = ((1, 1, 1), (0, 0.627, 1), (0.137, 0.235, 0.98),
              (0.392, 0, 0.627), (0.784, 0, 0.627))
    # (0.1  , 0.1   , 0.784),
    levelsPrec = [0, 1, 3, 10, 30, 100.]

    # Loop over dates
    for idate, date in enumerate(make_datelist(inargs)):

        # Loop over times
        for t in make_timelist(timedelta(hours=inargs.time_start),
                               timedelta(hours=inargs.time_end),
                               timedelta(hours=1)):

            # Load all CU objects
            fobjlist = []
            titlelist = []

            # 1st: Radar
            fobjlist.append(get_and_crop_radar_fobj(inargs, date, t))
            titlelist.append('Radar')

            # 2nd: det
            ncdffn_pref = (get_config(inargs, 'paths', 'raw_data') + date +
                           '/deout_ceu_pspens/' + 'det' + '/OUTPUT/lfff')
            fobjlist.append(
                getfobj_ncdf(ncdffn_pref + ddhhmmss(t) + '.nc_30m_surf',
                             'PREC_ACCUM'))
            titlelist.append('Det')

            # 3rd: ens
            ncdffn = 'lfff' + ddhhmmss(t) + '.nc_30m_surf'
            date_dir = (get_config(inargs, 'paths', 'raw_data') + date +
                        '/deout_ceu_pspens/')
            fobjlist.extend(
                getfobj_ncdf_ens(date_dir,
                                 'sub',
                                 inargs.nens,
                                 ncdffn,
                                 dir_suffix='/OUTPUT/',
                                 fieldn='PREC_ACCUM',
                                 nfill=1))
            titlelist.extend(['Mem ' + str(i + 1) for i in range(inargs.nens)])

            # Now plot
            n_panels = len(fobjlist)
            n_cols = 4
            n_rows = int(np.ceil(float(n_panels) / n_cols))
            fig, axmat = plt.subplots(n_rows,
                                      n_cols,
                                      figsize=(10, 3.5 * n_rows))
            axflat = np.ravel(axmat)

            for i in range(len(fobjlist)):
                plt.sca(axflat[i])
                cf, tmp = ax_contourf(axflat[i],
                                      fobjlist[i],
                                      colors=cmPrec,
                                      pllevels=levelsPrec,
                                      ji0=(50 + inargs.zoom_lat1,
                                           50 + inargs.zoom_lon1),
                                      ji1=(357 - 51 + inargs.zoom_lat2,
                                           357 - 51 + inargs.zoom_lon2),
                                      sp_title=titlelist[i],
                                      Basemap_drawrivers=False,
                                      npars=0,
                                      nmers=0)
            cb = fig.colorbar(cf,
                              cax=fig.add_axes([0.4, 0.1, 0.2, 0.02]),
                              orientation='horizontal')
            cb.set_label('Accumulation [mm/h]')
        titlestr = (yyyymmddhh_strtotime(date).strftime(
            get_config(inargs, 'plotting', 'date_fmt')) + ' ' +
                    str(t.seconds / 3600).zfill(2) + 'UTC')
        fig.suptitle(titlestr)
        plt.tight_layout(rect=[0, 0.1, 1, 0.93])

        # Save figure and log
        save_fig_and_log(fig,
                         None,
                         inargs,
                         'prec_stamps',
                         date=date,
                         time=str(t.seconds / 3600).zfill(2))
Esempio n. 15
0
def plot_std_vs_mean(inargs):
    """
    Plots standard deviation versus mean plots.

    Parameters
    ----------
    inargs : argparse object
      Argparse object with all input arguments

    """

    dx = float(get_config(inargs, 'domain', 'dx'))
    c_red = get_config(inargs, 'colors', 'third')
    c_blue = get_config(inargs, 'colors', 'ens')
    # Load dataset
    rootgroup = read_netcdf_dataset(inargs)
    # The variables have dimensions [date, time, n, x[n], y[n]]

    # Set up figure
    aspect = 0.8
    pw = get_config(inargs, 'plotting', 'page_width')
    fig, ax = plt.subplots(1, 1, figsize=(pw / 2., pw / 2. * aspect))

    # Data processing
    var = inargs.std_vs_mean_var
    if var not in ['M', 'TTENS']:
        raise Exception('Wrong variable for std_vs_mean.')

    mx_ind = inargs.std_vs_mean_min_scale + 1
    std = np.sqrt(rootgroup.variables['var_' + var][:, :, :mx_ind, :, :])
    mean = rootgroup.variables['mean_' + var][:, :, :mx_ind, :, :]

    # Start with n loop for CC06 fit
    fit_list = []
    for i_n, n in enumerate(rootgroup.variables['n'][:mx_ind]):
        if inargs.std_vs_mean_var == 'TTENS':
            # Multiply with area
            std[:, :, i_n, :, :] *= (n * dx)**2
            mean[:, :, i_n, :, :] *= (n * dx)**2
        tmp_std = np.ravel(std[:, :, i_n, :, :])
        tmp_mean = np.ravel(mean[:, :, i_n, :, :])
        fit_list.append(fit_curve(tmp_mean, tmp_std))

    # Bin all the data
    std = np.ravel(std)
    mean = np.ravel(mean)

    mask = np.isfinite(mean)

    std = std[mask]
    mean = mean[mask]

    print np.min(mean), np.max(mean)
    # Fit curves for entire dataset
    sqrt_fit = fit_curve(mean, std)
    lin_fit = fit_curve(mean, std, 'linear')
    tmp_x = np.logspace(1, 12, 1000)
    ax.plot(tmp_x,
            np.sqrt(sqrt_fit * tmp_x),
            alpha=1,
            c=c_red,
            linestyle='-',
            zorder=0.2,
            label=r'CC06: $y=\sqrt{bx}$')
    ax.plot(tmp_x,
            lin_fit * tmp_x,
            alpha=1,
            color=c_blue,
            linestyle='--',
            zorder=0.2,
            label=r'SPPT: $y = bx$')

    nbins = 10
    if inargs.std_vs_mean_var == 'M':
        binedges = np.logspace(6.7, 10, nbins + 1)
    elif inargs.std_vs_mean_var == 'TTENS':
        binedges = np.logspace(1, 8, nbins + 1)
    if inargs.var == 'prec':
        binedges = np.logspace(5, 10, nbins + 1)
    bininds = np.digitize(mean, binedges)
    binmeans = []
    bin5 = []
    bin25 = []
    bin75 = []
    bin95 = []
    binnum = []
    for i in range(1, nbins + 1):
        num = (std[bininds == i]).shape[0]
        if num == 0:
            binmeans.append(np.nan)
            bin25.append(np.nan)
            bin75.append(np.nan)
            bin5.append(np.nan)
            bin95.append(np.nan)
        else:
            binmeans.append(np.average(std[bininds == i]))
            bin25.append(np.percentile(std[bininds == i], 25))
            bin75.append(np.percentile(std[bininds == i], 75))
            bin5.append(np.percentile(std[bininds == i], 5))
            bin95.append(np.percentile(std[bininds == i], 95))
        # I cannot remember what that rescaling of the number was for
        # binnum.append(num / float((std[np.isfinite(std)]).shape[0]) * 50)
        binnum.append(num)
    print binnum
    # xmean = (binedges[:-1] + binedges[1:]) / 2.
    logmean = np.exp((np.log(binedges[:-1]) + np.log(binedges[1:])) / 2.)
    logdiff = np.diff(np.log(binedges))[0]
    logleft = np.exp(np.log(binedges[:-1]) + 0.2 * logdiff)
    logright = np.exp(np.log(binedges[1:]) - 0.2 * logdiff)
    height = np.array(bin75) - np.array(bin25)
    width = logright - logleft

    ax.bar(logleft,
           height,
           width,
           bin25,
           linewidth=1.3,
           color='gray',
           edgecolor='gray',
           align='edge')
    for i, binmean in enumerate(binmeans):
        ax.plot([logleft[i], logright[i]], [binmean, binmean],
                color='black',
                zorder=2)
        ax.plot([logmean[i], logmean[i]], [bin5[i], bin95[i]],
                color='black',
                zorder=0.5)

    if inargs.std_vs_mean_var == 'M':
        ax.set_xlim(10**6.7, 1e10)
        ax.set_ylim(0.8e7, 2e9)
        ax.set_xlabel(r'$\langle M \rangle$ [kg s$^{-1}$]')
        ax.set_ylabel(r'$\mathrm{std}(M)$ [kg s$^{-1}$]')
    else:
        ax.set_xlim(1e1, 1e8)
        ax.set_ylim(1e2, 7e6)
        ax.set_xlabel(r'$\langle Q \rangle \times A$ [K s$^{-1}$ m$^{2}$]')
        ax.set_ylabel(r'$\mathrm{std}(Q \times A)$ [K s$^{-1}$ m$^{2}$]')

    ax.set_xscale('log')
    ax.set_yscale('log')
    print('Sqrt fit = %.2f' % (sqrt_fit))
    titlestr = 'a) Mass flux' if inargs.std_vs_mean_var == 'M' \
        else 'b) Heating rate'
    ax.set_title(titlestr + ' scaling')

    ax.legend(loc=2, ncol=1, prop={'size': 8})

    ax.spines['top'].set_visible(False)
    ax.spines['right'].set_visible(False)
    ax.spines['left'].set_position(('outward', 3))
    ax.spines['bottom'].set_position(('outward', 3))

    if inargs.std_vs_mean_plot_inlay:
        if inargs.std_vs_mean_var == 'TTENS':
            raise Exception('Does not work because of line fitting.')
        ax2 = plt.axes([.72, .25, .2, .2], axisbg='lightgray')
        blist = np.array(fit_list) / 1.e8
        x = np.array(rootgroup.variables['n'][:mx_ind]) * dx / 1000.

        ax2.plot(x, blist, c=c_red)
        ax2.scatter(x, blist, c=c_red, s=20)
        ax2.set_title('Slope of CC06 fit', fontsize=7)
        ax2.set_ylabel(r'$b\times 10^8$', fontsize=6, labelpad=0.05)
        ax2.set_xlabel('n [km]', fontsize=6, labelpad=0.07)
        ax2.set_xscale('log')
        ax2.set_xlim(10, 1200)
        from matplotlib.ticker import StrMethodFormatter, NullFormatter
        ax2.xaxis.set_major_formatter(StrMethodFormatter('{x:.0f}'))
        ax2.xaxis.set_minor_formatter(NullFormatter())
        ax2.set_xticks([10, 100, 1000])
        ax2.set_xticklabels([10, 100, 1000], fontsize=6)
        ax2.set_yticks([0.5, 1.5])
        ax2.set_yticklabels([0.5, 1.5], fontsize=6)

    plt.subplots_adjust(left=0.17, right=0.95, bottom=0.17, top=0.92)

    # Save figure and log
    save_fig_and_log(fig, rootgroup, inargs,
                     'std_vs_mean_' + inargs.std_vs_mean_var)
def plot_spectra(inargs):
    """
    For now this loads previously computed files.

    Returns
    -------

    """
    savesuf = '_ana-spectra_wat-True_height-3000_nens-50_tstart-3_tend-24_tinc-180_minmem-5_dr-2.nc'
    # Load data
    dke_spec_list = []
    bgke_spec_list = []
    dprec_spec_list = []
    bgprec_spec_list = []
    for d in make_datelist(inargs):
        dataset = Dataset(inargs.preproc_dir + d + savesuf, 'r')
        dke_spec_list.append(dataset.variables['dkespec'][:])
        bgke_spec_list.append(dataset.variables['bgkespec'][:])
        dprec_spec_list.append(dataset.variables['dprecspec'][:])
        bgprec_spec_list.append(dataset.variables['bgprecspec'][:])
    dke_spec = np.nanmean(dke_spec_list, axis = 0)
    bgke_spec = np.nanmean(bgke_spec_list, axis = 0)
    dprec_spec = np.nanmean(dprec_spec_list, axis = 0)
    bgprec_spec = np.nanmean(bgprec_spec_list, axis = 0)
    timelist = [timedelta(seconds=ts) for ts in dataset.variables['time']]
    timelist_plot = [(dt.total_seconds() / 3600) for dt in timelist]

    # Define colors
    cyc = [plt.cm.jet(i) for i in np.linspace(0, 1, len(timelist))]
    cyc = ("#E7A7FF", "#FF84DB", "#EF8974", "#AF9300", "#529324", "#008768",
           "#006C88", "#2D3184")
    speclam = dataset.variables['speclam'][:]

    # Set up figures
    for diff, bg, name in zip([dke_spec, dprec_spec],
                              [bgke_spec, bgprec_spec],
                              ['Kinetic energy', 'Precipitation']):
        pw = get_config(inargs, 'plotting', 'page_width')
        width_fraction = 3. / 9.
        ratio = 1.
        fig, ax = plt.subplots(1, 1, figsize=(pw * width_fraction,
                                              pw * width_fraction * ratio))

        ############# Time loop ##############
        for it, t in enumerate(timelist):
            print 'time: ', t
            # Get ratio
            ratio = diff[it] / bg[it] / 2.
            ax.plot(speclam / 1000., ratio, c=cyc[it],
                       label=str(int(timelist_plot[it])).zfill(2),
                       linewidth=1.5)

        ax.legend(loc=3, ncol=2, fontsize=8, title='Time [UTC]')
        ax.plot([5, 1000.], [1, 1], c='gray', alpha=0.5)
        ax.set_xlabel('Wavelength [km]')
        # ax.set_ylabel('Saturation ratio')
        # ax.set_title("Saturation of KE spectrum")
        ax.set_ylim(1e-2, 1.1)
        ax.set_xlim(5, 1000.)
        ax.set_yscale('log')
        ax.set_xscale('log')
        ax.spines['top'].set_visible(False)
        ax.spines['right'].set_visible(False)
        ax.spines['bottom'].set_position(('outward', 3))
        ax.spines['left'].set_position(('outward', 3))
        plt.yticks(rotation=90)

        plt.subplots_adjust(left=0.15, right=0.95, bottom=0.3, top=0.85)

        save_fig_and_log(fig, None, inargs, name[:4], tight=False)
Esempio n. 17
0
def plot_domain_mean_timeseries_individual(inargs, plot_var):
    """
    Function to plot time series of domain mean precipitation for each day

    Parameters
    ----------
    inargs : argparse object
      Argparse object with all input arguments
    plot_var : str
      Type of plot. Must be 'precipitation' or 'cape_tauc'

    """

    assert plot_var in ['precipitation', 'cape_tauc'], \
        'Type must be precipitation or cape_tauc'

    # Read pre-processed data
    rootgroup = read_netcdf_dataset(inargs)
    n_days = rootgroup.dimensions['date'].size

    # Set up figure
    n_cols = 4
    n_rows = int(np.ceil(float(n_days) / n_cols))

    fig, axmat = plt.subplots(n_rows, n_cols, sharex=True, sharey=True,
                              figsize=(get_config(inargs, 'plotting',
                                                  'page_width'),
                                       2.1 * n_rows))
    axflat = np.ravel(axmat)

    # Loop over axes / days
    for iday in range(n_days):
        ax = axflat[iday]
        dateobj = (timedelta(seconds=int(rootgroup.variables['date'][iday])) +
                   datetime(1, 1, 1))
        datestr = dateobj.strftime(get_config(inargs, 'plotting', 'date_fmt'))
        if not iday == 0:
            ax.text(0.3, 0.9, datestr, fontsize=10, transform = ax.transAxes)
        else:
            ax.text(0.65, 0.9, datestr, fontsize=10, transform = ax.transAxes)
        if iday >= ((n_cols * n_rows) - n_cols):  # Only bottom row
            ax.set_xlabel('Time [UTC]')
            ax.set_xticks([0, 6, 12, 18, 24])

        if plot_var == 'precipitation':
            plot_precipitation_panel(inargs, ax, iday, rootgroup)
        if plot_var == 'cape_tauc':
            plot_cape_tauc_panel(inargs, ax, iday, rootgroup)

        ax.set_ylim(0, inargs.ymax)
        ax.spines['top'].set_visible(False)
        ax.spines['right'].set_visible(False)
        # ax.spines['left'].set_position(('outward', 3))
        ax.spines['bottom'].set_position(('outward', 3))

    # Finish figure
    axflat[0].legend(loc=2)
    plt.tight_layout()
    plt.subplots_adjust(wspace=0.15, hspace=0.25)

    # Save figure
    save_fig_and_log(fig, rootgroup, inargs, plot_var + '_ts_individual')
Esempio n. 18
0
    if args.obs == 'AIREP':
        axarr1[0].set_ylabel('Height agu [m]')
        axarr2[0].set_ylabel('Height agu [m]')
        axarr1[0].set_ylim(0, 10000)
        axarr1[1].set_ylim(0, 10000)
        axarr2[0].set_ylim(0, 10000)
        axarr2[1].set_ylim(0, 10000)

    for axarr in [axarr1, axarr2]:
        plt.sca(axarr[0])
        plt.tight_layout(rect=[0, 0.0, 1, 0.97])

    fig1.suptitle(args.obs + ' ' + args.var + ' RMSE', fontsize=10)
    fig2.suptitle(args.obs + ' ' + args.var + ' BIAS', fontsize=10)

    save_fig_and_log(fig1, 'rmse_' + plotstr, plotdir)
    save_fig_and_log(fig2, 'bias_' + plotstr, plotdir)

    plt.close('all')

if args.obs == 'SYNOP':
    ax.set_xlabel('time')
    ax.set_ylabel(args.var + ' [' + unitdict[args.var] + ']')
    ax.legend(loc=0, fontsize=8)
    ax.axhline(y=0, zorder=0.1, c='gray')

    ax.set_title(plotstr + '\n RMSE (solid), Bias (dotted)')
    plt.tight_layout()
    save_fig_and_log(fig, plotstr, plotdir)
    plt.close('all')
Esempio n. 19
0
def plot_domain_mean_timeseries_composite(inargs, plot_var):
    """
    Function to plot time series of domain mean as a composite over 
    all days

    Parameters
    ----------
    inargs : argparse object
      Argparse object with all input arguments
    plot_var : str
      Type of plot. Must be 'precipitation' or 'cape_tauc'

    """

    assert plot_var in ['precipitation', 'cape_tauc', 'prec_cape'], \
        'Wrong type!'

    # Read pre-processed data
    rootgroup = read_netcdf_dataset(inargs)
    x = rootgroup.variables['time'][:]

    pw = get_config(inargs, 'plotting', 'page_width')
    ratio = 0.7
    fig, ax1 = plt.subplots(1, 1, figsize=(pw / 2., pw / 2. * ratio))

    if plot_var in ['precipitation', 'prec_cape']:
        ax1.set_ylabel(r'Precip [mm h$^{-1}$]')
        for group in rootgroup.groups:
            array = rootgroup.groups[group].variables['PREC_ACCUM'][:]
            mean = np.mean(array, axis=(0, 2))
            std = np.mean(np.std(array, axis=2, ddof=1), axis=0)
            ax1.plot(x, mean, label=group,
                     c=get_config(inargs, 'colors', group),
                     linewidth=2)
            if group == 'ens':
                lower = mean - std
                upper = mean + std
                ax1.fill_between(x, lower, upper, where=upper >= lower,
                                 facecolor=get_config(inargs, 'colors',
                                                      'ens_range'))
        if plot_var == 'prec_cape':
            ax2 = ax1.twinx()
            ax2.set_ylabel(r'CAPE [J kg$^{-1}$]')

            array = rootgroup.groups['ens'].variables['CAPE_ML'][:]
            mean = np.mean(array, axis=(0, 2))
            ax2.plot(x, mean, c=get_config(inargs, 'colors', 'third'),
                     linestyle='--', linewidth=2)

    if plot_var == 'cape_tauc':
        ax1.set_ylabel('CAPE [J/kg]')
        ax2 = ax1.twinx()
        ax2.set_ylabel('tau_c [h]')
        for group in ['det', 'ens']:
            for var, ax, ls in zip(['CAPE_ML', 'TAU_C'],
                                   [ax1, ax2],
                                   ['-', '--']):
                array = rootgroup.groups[group].variables[var][:]
                mean = np.mean(array, axis=(0, 2))
                ax.plot(x, mean, label=group,
                        c=get_config(inargs, 'colors', group), ls=ls)

    ax1.set_xlabel('Time [UTC]')
    ax1.set_xticks([0, 6, 12, 18, 24])
    ax1.axvline(6, c='lightgray', linewidth=0.5, zorder = 0.001)
    for ax in [ax1, ax2]:
        ax.spines['top'].set_visible(False)
        ax.spines['bottom'].set_position(('outward', 3))
        ax.spines['left'].set_position(('outward', 3))
        ax.spines['right'].set_position(('outward', 3))
        ax.set_xlim((0, 24))

    # comp_str = 'Composite ' + get_composite_str(inargs, rootgroup)
    ax1.set_title('Composite precipitation')
    ax1.legend(loc=0, fontsize=8, title='Precip')

    plt.subplots_adjust(left=0.18, right=0.82, bottom=0.2, top=0.9)

    # Save figure and log
    save_fig_and_log(fig, rootgroup, inargs, plot_var + '_ts_composite')
def plot_prec_stamps(inargs):
    """
    Plots precipitation stamps of obs, det and ensemble every hour for each
    date and time specified

    Parameters
    ----------
    inargs : argparse object
      Argparse object with all input arguments

    """

    # Loop over dates
    for idate, date in enumerate(make_datelist(inargs)):
        print('Date ' + date)
        # Loop over times
        for t in make_timelist(timedelta(hours=inargs.time_start),
                               timedelta(hours=inargs.time_end),
                               timedelta(hours=1)):
            print('Time ' + str(t))
            # Load all CU objects
            fobjlist = []
            titlelist = []

            # 1st: Radar
            radarpref = (get_config(inargs, 'paths', 'radar_data') +
                         get_config(inargs, 'paths', 'radar_prefx'))
            radarsufx = get_config(inargs, 'paths', 'radar_sufix')
            dtradar = timedelta(minutes=10)

            radartime = yymmddhhmm(yyyymmddhh_strtotime(date) + t - dtradar)
            radarfn = radarpref + radartime + radarsufx
            radar_fobj = getfobj_ncdf(radarfn, fieldn='pr', dwdradar=True)
            # Crop data
            l11, l12, l21, l22, l11_rad, l12_rad, l21_rad, l22_rad = \
                get_domain_limits(inargs)
            l11_diff = l11_rad - l11
            l12_diff = l12_rad - l12
            l21_diff = l21_rad - l21
            l22_diff = l22_rad - l22
            radar_fobj.data = radar_fobj.data[l11_diff:l12_diff,
                                              l21_diff:l22_diff]
            radar_fobj.lats = radar_fobj.lats[l11_diff:l12_diff,
                                              l21_diff:l22_diff]
            radar_fobj.lons = radar_fobj.lons[l11_diff:l12_diff,
                                              l21_diff:l22_diff]
            fobjlist.append(radar_fobj)
            titlelist.append('Radar')

            # 2nd: det
            ncdffn_pref = (get_config(inargs, 'paths', 'raw_data') + date +
                           '/deout_ceu_pspens/' + 'det' + '/OUTPUT/lfff')
            fobjlist.append(
                getfobj_ncdf(ncdffn_pref + ddhhmmss(t) + '.nc_30m_surf',
                             'PREC_ACCUM'))
            titlelist.append('Det')

            # 3rd: ens
            ncdffn = 'lfff' + ddhhmmss(t) + '.nc_30m_surf'
            date_dir = (get_config(inargs, 'paths', 'raw_data') + date +
                        '/deout_ceu_pspens/')
            fobjlist.extend(
                getfobj_ncdf_ens(date_dir,
                                 'sub',
                                 inargs.nens,
                                 ncdffn,
                                 dir_suffix='/OUTPUT/',
                                 fieldn='PREC_ACCUM',
                                 nfill=1))
            titlelist.extend(
                ['Member ' + str(i + 1) for i in range(inargs.nens)])

            # Now plot
            n_panels = len(fobjlist)
            n_cols = 4
            n_rows = int(np.ceil(float(n_panels) / n_cols))

            pw = get_config(inargs, 'plotting', 'page_width')
            fig, axmat = plt.subplots(n_rows,
                                      n_cols,
                                      figsize=(pw, 3.0 * n_rows))
            axflat = np.ravel(axmat)

            for i in range(len(fobjlist)):
                plt.sca(axflat[i])
                cf = plot_stamp(inargs, fobjlist[i], cmPrec, levelsPrec,
                                axflat[i], 'PREC_ACCUM')
                axflat[i].set_title(titlelist[i])
            cb = fig.colorbar(cf,
                              cax=fig.add_axes([0.4, 0.15, 0.2, 0.02]),
                              orientation='horizontal')
            cb.set_label('Accumulation [mm/h]')
            titlestr = ((yyyymmddhh_strtotime(date) +
                         t).strftime('%d %b - %H UTC'))
            fig.suptitle(titlestr)
            plt.subplots_adjust(wspace=0.02, left=0.02, right=0.98)

            # Save figure and log
            save_fig_and_log(fig,
                             None,
                             inargs,
                             'prec_stamps',
                             datestr=((yyyymmddhh_strtotime(date) +
                                       t).strftime('%Y%m%d_%H')))
Esempio n. 21
0
def plot_domain_mean_timeseries_composite(inargs, plot_type):
    """
    Function to plot time series of domain mean as a composite over 
    all days

    Parameters
    ----------
    inargs : argparse object
      Argparse object with all input arguments
    plot_type : str
      Type of plot. Must be 'precipitation' or 'cape_tauc'

    """

    assert plot_type in ['precipitation', 'cape_tauc'], \
        'Type must be precipitation or cape_tauc'

    # Read pre-processed data
    rootgroup = read_netcdf_dataset(inargs)
    x = rootgroup.variables['time'][:]

    fig, ax1 = plt.subplots(1, 1, figsize=(3, 3))

    if plot_type == 'precipitation':
        ax1.set_ylabel('Accumulation [mm/h]')
        for group in rootgroup.groups:
            array = rootgroup.groups[group].variables['PREC_ACCUM'][:]
            mean = np.mean(array, axis=(0, 2))
            ax1.plot(x,
                     mean,
                     label=group,
                     c=get_config(inargs, 'colors', group))

    if plot_type == 'cape_tauc':
        ax1.set_ylabel('CAPE [J/kg]')
        ax2 = ax1.twinx()
        ax2.set_ylabel('tau_c [h]')
        for group in ['det', 'ens']:
            for var, ax, ls in zip(['CAPE_ML', 'TAU_C'], [ax1, ax2],
                                   ['-', '--']):
                array = rootgroup.groups[group].variables[var][:]
                mean = np.mean(array, axis=(0, 2))
                ax.plot(x,
                        mean,
                        label=group,
                        c=get_config(inargs, 'colors', group),
                        ls=ls)

    ax1.set_xlabel('Time [UTC]')
    dateobj_start = (timedelta(seconds=int(rootgroup.variables['date'][0])) +
                     datetime(1, 1, 1))
    datestr_start = dateobj_start.strftime(
        get_config(inargs, 'plotting', 'date_fmt'))
    dateobj_end = (timedelta(seconds=int(rootgroup.variables['date'][-1])) +
                   datetime(1, 1, 1))
    datestr_end = dateobj_end.strftime(
        get_config(inargs, 'plotting', 'date_fmt'))
    comp_str = 'Composite ' + datestr_start + ' - ' + datestr_end

    ax1.set_title(comp_str)
    ax1.legend(loc=0)

    plt.tight_layout()

    # Save figure and log
    save_fig_and_log(fig, rootgroup, inargs, plot_type + '_ts_composite')