Example #1
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)
Example #2
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')
Example #3
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')
Example #4
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)
Example #5
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)
Example #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))
Example #7
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')
Example #8
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')
Example #9
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')
Example #10
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')
Example #11
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')
Example #12
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')
Example #13
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')