def compute_CP_Q(dTh, p, rho0_stats, rstar, zstar, path):
    print(os.path.join(path, 'ColdPoolDry_single_3D.in'))
    nml = simplejson.loads(
        open(os.path.join(path, 'ColdPoolDry_single_3D.in')).read())
    nx = nml['grid']['nx']
    dx = nml['grid']['dx']
    dV = dx**3
    ic = nml['init']['ic']
    imin = np.int(ic - (rstar + 1000) / dx)
    imax = nx - imin
    kmax = np.int((zstar + 1000.) / dx)

    root = nc.Dataset(os.path.join(path, 'fields', '0.nc'))
    s_ = root.groups['fields']['s'][imin:imax, imin:imax, :kmax]
    root.close()

    theta = thetas_c(s_, 0.0)
    Th_ref = Tg  # at surface, temperature equal to pot. temp. (Tg=Theta_g)
    dtheta = np.where((theta - Th_ref) < -0.05, theta - Th_ref, 0)

    Q = 0.
    for k in range(nz):
        dT = dTh / exner_c(p[k])
        Q += cpd * dT * (np.count_nonzero(dtheta[:, :, k]) * rho0_stats[k] *
                         dV)

    return Q
def compute_CP_vol_mass(rho0_stats, rstar, zstar, path):
    print(os.path.join(path, 'ColdPoolDry_single_3D.in'))
    nml = simplejson.loads(
        open(os.path.join(path, 'ColdPoolDry_single_3D.in')).read())
    nx = nml['grid']['nx']
    dx = nml['grid']['dx']
    dV = dx**3
    ic = nml['init']['ic']
    imin = np.int(ic - (rstar + 1000) / dx)
    imax = nx - imin
    kmax = np.int((zstar + 1000.) / dx)

    root = nc.Dataset(os.path.join(path, 'fields', '0.nc'))
    s_ = root.groups['fields']['s'][imin:imax, imin:imax, :kmax]
    root.close()

    theta = thetas_c(s_, 0.0)
    Th_ref = Tg  # at surface, temperature equal to pot. temp. (Tg=Theta_g)
    dTh = np.where((theta - Th_ref) < -0.05, theta - Th_ref, 0)
    m_CP = 0.
    # n_CP = 0.
    for k in range(kmax):
        # n_CP += np.count_nonzero(dTh[:,:,k])
        m_CP += np.count_nonzero(dTh[:, :, k]) * rho0_stats[k] * dV
    # print('nCP = '+str(n_CP), np.mean(rho0_stats[:kmax]))
    return m_CP
def compute_PE_from_simulation(dTh, rstar, zstar, Tg, path):
    nml = simplejson.loads(
        open(os.path.join(path, 'ColdPoolDry_single_3D.in')).read())
    nx = nml['grid']['nx']
    dx = nml['grid']['dx']
    dV = dx**3
    ic = nml['init']['ic']
    jc = nml['init']['jc']
    marg = nml['init']['marg']
    imin = np.int(ic - (rstar + 1000) / dx)
    imax = nx - imin
    ni = imax - imin
    ni2 = ni**2
    kmax = np.int((zstar + 1000.) / dx)
    print('computig PE: r*,z*', rstar, zstar, 'dz', dx)
    print('imin, imax, kmax', imin, imax, kmax, ic, jc)

    root = nc.Dataset(os.path.join(path, 'fields', '0.nc'))
    # temp_ = root.groups['fields']['temperature'][imin:imax, imin:imax, :kmax]
    s_ = root.groups['fields']['s'][imin:imax, imin:imax, :kmax]
    root.close()
    theta_ = thetas_c(s_, 0.0)
    root = nc.Dataset(
        os.path.join(path, 'stats', 'Stats.ColdPoolDry_single_3D.nc'))
    rho0_stats = root.groups['reference'].variables['rho0'][:kmax]
    # alpha0_stats = root.groups['reference'].variables['alpha0'][:kmax]
    zhalf_stats = root.groups['reference'].variables['z'][:kmax]
    # rho_unit = root.groups['reference'].variables['rho0'].units
    root.close()
    Th_ref = Tg  # at surface, temperature equal to pot. temp. (Tg=Theta_g)
    # # print('imin, imax, kmax: ', imin, imax, kmax)
    # # print('shape: ', ni, 200, theta_.shape)
    # # print('reference temperature: ', Th_ref, Tg, theta_[10,10,10])

    theta = theta_.reshape(ni2, kmax)
    print('reshaping: ', theta.shape, theta_.shape, zhalf_stats.shape,
          rho0_stats.shape, kmax)
    PE = 0.
    for i in range(ni2):
        for k in range(kmax):
            # PE += (Th_ref - theta[i, k]) * zhalf_stats[k] * rho_d[k] * dV
            PE += (Th_ref - theta[i, k]) * zhalf_stats[k] * rho0_stats[k] * dV
    PE = g / Th_ref * PE

    print('')
    return PE
def compute_CP_volume(rstar, zstar, Tg, path):
    nml = simplejson.loads(
        open(os.path.join(path, 'ColdPoolDry_single_3D.in')).read())
    nx = nml['grid']['nx']
    dx = nml['grid']['dx']
    dV = dx**3
    ic = nml['init']['ic']
    jc = nml['init']['jc']
    marg = nml['init']['marg']
    imin = np.int(ic - (rstar + 1000) / dx)
    imax = nx - imin
    i0 = np.int((imax - imin) / 2)
    ni = imax - imin
    ni2 = ni**2
    kmax = np.int((zstar + 1000.) / dx)

    root = nc.Dataset(os.path.join(path, 'fields', '0.nc'))
    # temp_ = root.groups['fields']['temperature'][imin:imax, imin:imax, :kmax]
    s_ = root.groups['fields']['s'][imin:imax, imin:imax, :kmax]
    root.close()
    theta = thetas_c(s_, 0.0)

    Th_ref = Tg  # at surface, temperature equal to pot. temp. (Tg=Theta_g)
    # dTh1 = theta - Th_ref
    # dTh2 = np.where((theta-Th_ref) < 0, theta-Th_ref, 0)
    dTh = np.where((theta - Th_ref) < -0.05, theta - Th_ref, 0)
    # CP_vol1 = np.count_nonzero(dTh1 < 0) * dV
    # CP_vol2 = np.count_nonzero(dTh2 < 0) * dV
    CP_vol = np.count_nonzero(dTh < 0) * dV

    # fig, (ax0, ax1, ax2, ax3) = plt.subplots(1, 4, figsize=(15, 4))
    # cf = ax0.contourf(theta_[i0,:,:].T)
    # plt.colorbar(cf, ax=ax0)
    # cf = ax1.contourf(dTh1[i0,:,:].T, levels=np.arange(np.amin(dTh1), 0, .01))
    # plt.colorbar(cf, ax=ax1)
    # cf = ax2.contourf(dTh2[i0,:,:].T, levels=np.arange(np.amin(dTh2), 0, .01))
    # plt.colorbar(cf, ax=ax2)
    # cf = ax3.contourf(dTh3[i0, :, :].T, levels=np.arange(np.amin(dTh3), 0, .01))
    # plt.colorbar(cf, ax=ax3)
    # plt.show()

    return CP_vol
def main():
    cm_rain = plt.cm.get_cmap('rainbow')
    cm_rep = plt.cm.get_cmap('prism')
    cm = cm_rain

    parser = argparse.ArgumentParser(prog='LES_CP')
    parser.add_argument("--dx")
    parser.add_argument("--dTh_min")
    parser.add_argument("--dTh_max")
    args = parser.parse_args()

    path_out = './figs_Initialization/'

    'surface values'
    Th_g = 300.0  # temperature for neutrally stratified background (value from Soares Surface)
    if args.dx:
        dx_ = np.int(args.dx)
    else:
        dx_ = 50
    marg = 200.
    z_half = define_geometry(dx_, marg)
    set_parameters()
    print('dx: ' + str(dx_))
    ''' Parameter range '''
    if args.dTh_min:
        dTh_min = np.int(args.dTh_min)
    else:
        dTh_min = 2
    if args.dTh_max:
        dTh_max = np.int(args.dTh_max)
    else:
        dTh_max = 4
    dTh_range = np.arange(dTh_min, dTh_max + 1)
    # for dx=100m, no matches for r*>4200m;
    # for dx=50m, matches for r*=..., 3600, 4900, 5000; no matches for r<400m
    rstar_min = 5e2
    rstar_max = 25e2
    zstar_min = 5e2
    zstar_max = 25e2
    rstar_range = np.arange(rstar_min, rstar_max + 100, 100)
    zstar_range = np.arange(zstar_min, zstar_max + 100, 1e2)
    n_thermo = len(dTh_range)
    n_geom_z = len(zstar_range)
    n_geom_r = len(rstar_range)
    print('dTh: ' + str(dTh_range))
    print('zstar: ' + str(zstar_range))
    print('rstar: ' + str(rstar_range))
    print('n_geom_z: ' + str(n_geom_z))
    print('n_geom_r: ' + str(n_geom_r))
    ''' PE scaling-range '''
    # scaling = [2**(-1), 2**0, 2**1, 2**2, 2**3]
    scaling = [2**0]
    print('scaling: ' + str(scaling))
    print('')
    ''' Reference case '''
    dTh_ref = 3
    rstar_ref = 1000
    zstar_ref = 1000
    if dx_ == 100:
        path_ref = '/nbi/ac/cond1/meyerbe/ColdPools/3D_sfc_fluxes_off/single_3D_noise/run2_dx100m/dTh3_z1000_r1000/'
    elif dx_ == 50:
        path_ref = '/nbi/ac/cond1/meyerbe/ColdPools/3D_sfc_fluxes_off/single_3D_noise/run3_dx50m/dTh3_z1000_r1000_nz240/'
    case_name = 'ColdPoolDry_single_3D'
    print('Reference case: ' + path_ref)
    rootgrp = nc.Dataset(
        os.path.join(path_ref, 'stats', 'Stats.' + case_name + '.nc'))
    rho0_stats = rootgrp.groups['reference'].variables['rho0'][:]
    # alpha0_stats = rootgrp.groups['reference'].variables['alpha0'][:]
    zhalf_stats = rootgrp.groups['reference'].variables['z'][:]
    rootgrp.close()
    print('')
    print('z-arrays:')
    print('z_half:', z_half[:20])
    print('z_half_stats:', zhalf_stats[:20])
    print('')
    ''' reference PE '''
    print('Reference case: ')
    z_max_arr, theta_z = compute_envelope(dTh_ref, Th_g, rstar_ref, zstar_ref,
                                          marg, z_half)
    PE_ref = compute_PE(theta_z, Th_g, zstar_ref, rho0_stats, zhalf_stats,
                        z_half)
    PE_ref_up, PE_ref_low = compute_PE_density_approx(
        dTh_ref, zstar_ref, rstar_ref, rho0_stats[0])  # upper limit
    # test reference numerically
    rootgrp_field = nc.Dataset(os.path.join(path_ref, 'fields', '0.nc'))
    s0 = rootgrp_field.groups['fields'].variables['s'][:, :, :]
    rootgrp_field.close()
    ic_ = s0.shape[0] / 2
    jc_ = s0.shape[1] / 2
    theta = thetas_c(s0, 0.0)[ic_ - nx / 2:ic_ + nx / 2,
                              jc_ - ny / 2:jc_ + ny / 2, :nz]
    PE_ref_num = compute_PE(theta, Th_g, zstar_ref, rho0_stats, zhalf_stats,
                            z_half)
    del s0
    print('  (from envel.) PE_ref =        ' + str(PE_ref))
    print('  (from field)  PE_ref_num =    ' + str(PE_ref_num))
    print('   difference: ' + str((PE_ref - PE_ref_num) / PE_ref))
    print('')
    print('   (upper limit)  PE_up = ' + str(PE_ref_up))
    print('   (lower limit)  PE_low = ' + str(PE_ref_low))
    print('   difference: ' + str((PE_ref - PE_ref_up) / PE_ref))
    print('   difference: ' + str((PE_ref - PE_ref_low) / PE_ref))
    print('')

    # theta_diff = theta_z - theta
    # PE_ref_diff = compute_PE(theta_diff+Th_g, Th_g, zstar_ref, rho0_stats, zhalf_stats)
    # print('theta noise: ', np.mean(theta))
    # print('theta diff: ', np.amax(theta_diff), np.amin(theta_diff), np.mean(theta_diff))
    # print('PE_ref:      ', PE_ref)
    # print('PE_ref_num:  ', PE_ref_num)
    # print('PE_ref_diff: ', PE_ref_diff)
    # print('diff PE:     ', PE_ref - PE_ref_num)

    # fig_name = 'PE_ref.png'
    # fig, axes = plt.subplots(2,3, figsize=(12,10))
    # kmax = np.int(zstar_ref/dz) + 10
    # y0 = np.int(theta_z.shape[1]/2)
    # lvls = np.linspace(296.5, 300.5, 1e2)
    # ax = axes[0,0]
    # cf = ax.contourf(theta_z[:,y0,:kmax].T, levels=lvls, vmin=296.5, vmax=300.1)
    # plt.colorbar(cf, ax=ax)
    # ax.set_title(str(theta_z[1,1,50])+', '+str(y0))
    # ax = axes[0,1]
    # cf = ax.contourf(theta[:,y0,:kmax].T, levels=lvls, vmin=296.5, vmax=300.1)
    # ax.set_title(str(theta[1,1,50])+', '+str(y0))
    # plt.colorbar(cf, ax=ax)
    # ax = axes[0,2]
    # cf = ax.contourf(theta_diff[:,y0,:kmax].T)
    # plt.colorbar(cf, ax=ax)
    #
    # ax = axes[1,0]
    # ax.contourf(theta_z[:,:,0].T)
    # ax.plot([0,nx], [y0, y0], 'k-')
    # ax.plot([ic,ic],[0,ny], 'k-')
    # ax = axes[1,1]
    # ax.contourf(theta[:,:,0].T)
    # ax.plot([0,nx], [y0, y0], 'k-')
    # ax.plot([ic,ic],[0,ny], 'k-')
    # plt.suptitle('y='+str(y0))
    # plt.savefig(os.path.join(path_out, fig_name))
    # plt.close()
    # del theta
    # del z_max_arr, theta_z

    for dTh in dTh_range:
        print('--- dTh=' + str(dTh))
        PE_range = np.zeros(len(scaling), dtype=np.single)
        fig1, (ax1, ax2, ax3) = plt.subplots(1, 3, figsize=(20, 10))
        fig2, (ax1_, ax2_, ax3_) = plt.subplots(1, 3, figsize=(20, 10))
        fig3, (a1, a2) = plt.subplots(1, 2, figsize=(20, 10))
        ax1.plot(zstar_range, PE_ref * np.ones(n_geom_z), 'k-', linewidth=3)
        ax2.plot(zstar_range, np.ones(n_geom_z), 'k-', linewidth=3)
        ax1_.plot(rstar_range, PE_ref * np.ones(n_geom_r), 'k-', linewidth=3)
        ax2_.plot(rstar_range, PE_ref * np.ones(n_geom_r), 'k-', linewidth=3)
        a2.plot(rstar_range, PE_ref * np.ones(n_geom_r), 'k-', linewidth=3)

        PE = np.zeros((n_geom_z, n_geom_r))
        # params = np.zeros(4)  # PE[dTh,r*], dTh, r*, res
        params_dict = {}
        count = np.ones(len(scaling))
        for i, s in enumerate(scaling):
            print('s=' + str(s), i)
            params_dict[str(s)] = np.zeros((1, 4))
            PE_range[i] = PE_ref * s
            ax1.plot(zstar_range,
                     PE_range[i] * np.ones(n_geom_z),
                     'k-',
                     linewidth=1.5)
            ax2.plot(zstar_range,
                     PE_range[i] * np.ones(n_geom_z) / PE_ref,
                     'k-',
                     linewidth=1.5)
            ax1.fill_between([zstar_range[0], zstar_range[-1]],
                             scaling[i] * PE_ref * 0.9,
                             scaling[i] * PE_ref * 1.1,
                             color='gray',
                             alpha=0.2,
                             label=r'$\pm 10$%$')
            ax1.fill_between([zstar_range[0], zstar_range[-1]],
                             scaling[i] * PE_ref * 0.95,
                             scaling[i] * PE_ref * 1.05,
                             color='gray',
                             alpha=0.4,
                             label=r'$\pm 5$%$')
            ax2.fill_between([zstar_range[0], zstar_range[-1]],
                             scaling[i] - 0.1,
                             scaling[i] + 0.1,
                             color='gray',
                             alpha=0.4,
                             label=r'$\pm$ 0.1 PE_ref')
            ax3.fill_between([zstar_range[0], zstar_range[-1]],
                             scaling[i] - 0.1,
                             scaling[i] + 0.1,
                             color='gray',
                             alpha=0.4,
                             label=r'$\pm$ 0.1 PE_ref')
            ax1_.plot(rstar_range,
                      PE_range[i] * np.ones(n_geom_r),
                      'k-',
                      linewidth=1.5)
            ax2_.plot(rstar_range,
                      PE_range[i] * np.ones(n_geom_r) / PE_ref,
                      'k-',
                      linewidth=1.5)
            a2.plot(rstar_range,
                    PE_range[i] * np.ones(n_geom_r) / PE_ref,
                    'k-',
                    linewidth=1.5)
            ax1_.fill_between([rstar_range[0], rstar_range[-1]],
                              scaling[i] * PE_ref * 0.9,
                              scaling[i] * PE_ref * 1.1,
                              color='gray',
                              alpha=0.2,
                              label=r'$\pm 10$%$')
            ax1_.fill_between([rstar_range[0], rstar_range[-1]],
                              scaling[i] * PE_ref * 0.95,
                              scaling[i] * PE_ref * 1.05,
                              color='gray',
                              alpha=0.4,
                              label=r'$\pm 5$%$')
            ax2_.fill_between([rstar_range[0], rstar_range[-1]],
                              scaling[i] - 0.1,
                              scaling[i] + 0.1,
                              color='gray',
                              alpha=0.4,
                              label=r'$\pm$ 0.1 PE_ref')
            ax3_.fill_between([rstar_range[0], rstar_range[-1]],
                              scaling[i] - 0.1,
                              scaling[i] + 0.1,
                              color='gray',
                              alpha=0.4,
                              label=r'$\pm$ 0.1 PE_ref')
            a2.fill_between([rstar_range[0], rstar_range[-1]],
                            scaling[i] - 0.1,
                            scaling[i] + 0.1,
                            color='gray',
                            alpha=0.4,
                            label=r'$\pm$ 0.1 PE_ref')
            if s == scaling[-1]:
                ax2.fill_between([zstar_range[0], zstar_range[-1]],
                                 scaling[i] - 0.25,
                                 scaling[i] + 0.25,
                                 color='gray',
                                 alpha=0.2,
                                 label=r'$\pm$ 0.25 PE_ref')
                ax2_.fill_between([rstar_range[0], rstar_range[-1]],
                                  scaling[i] - 0.25,
                                  scaling[i] + 0.25,
                                  color='gray',
                                  alpha=0.2,
                                  label=r'$\pm$ 0.25 PE_ref')
                a2.fill_between([rstar_range[0], rstar_range[-1]],
                                scaling[i] - 0.25,
                                scaling[i] + 0.25,
                                color='gray',
                                alpha=0.2,
                                label=r'$\pm$ 0.25 PE_ref')
        ''' compute PE '''
        print('compute PE for: ')
        for ir, rstar in enumerate(rstar_range):
            # while (ir<n_geom_r) and (PE[iz, ir] - PE_range[0])<0:
            rstar = rstar_range[ir]
            icol = np.double(np.mod(
                ir,
                np.double(n_geom_r) / 3)) / (np.double(n_geom_r) / 3)
            # for iz, zstar in enumerate(zstar_range):
            iz = 0
            while (iz < n_geom_z) and (PE[iz, ir] - PE_ref) <= 0:
                zstar = zstar_range[iz]
                print('r*=' + str(rstar) + ', z*=' + str(zstar))
                z_max_arr, theta = compute_envelope(dTh, Th_g, rstar, zstar,
                                                    marg, z_half)
                PE[iz, ir] = compute_PE(theta, Th_g, zstar, rho0_stats,
                                        zhalf_stats, z_half)
                print('PE-PE_ref: ' + str(PE[iz, ir] - PE_ref))
                for i, s in enumerate(scaling):
                    res = np.abs(PE[iz, ir] - PE_range[i]) / PE_range[i]
                    if res < 0.08:
                        count[i] += 1
                        params_dict[str(s)] = np.append(
                            params_dict[str(s)],
                            [PE[iz, ir], zstar, rstar, res]).reshape(
                                count[i], 4)
                iz += 1

            ax1.plot(zstar_range, PE[:, ir], '-o', color=cm(icol))
            ax2.plot(zstar_range,
                     PE[:, ir] / PE_ref,
                     '-o',
                     color=cm(icol),
                     label='r*=' + str(np.int(rstar)))
            ax3.plot(zstar_range, PE[:, ir] / PE_ref, '-', color='gray')
        for iz, zstar in enumerate(zstar_range):
            icol2 = np.double(iz) / n_geom_z
            ax1_.plot(rstar_range, PE[iz, :], '-o', color=cm(icol2))
            ax2_.plot(rstar_range,
                      PE[iz, :] / PE_ref,
                      '-o',
                      color=cm(icol2),
                      label='z*=' + str(np.int(zstar)))
            ax3_.plot(rstar_range, PE[iz, :] / PE_ref, '-', color='gray')
            a2.plot(rstar_range,
                    PE[iz, :] / PE_ref,
                    '-o',
                    color=cm(icol2),
                    label='z*=' + str(np.int(zstar)))

        print('plotting')
        for i, s in enumerate(scaling):
            for j in range(1, np.int(count[i])):
                pe = params_dict[str(s)][j, 0]
                zs = params_dict[str(s)][j, 1]
                rs = params_dict[str(s)][j, 2]
                res = params_dict[str(s)][j, 3]
                ax3.plot(zs,
                         pe / PE_ref,
                         'o',
                         color=cm(res * 10),
                         label='s=' + str(np.round(s, 1)) + ', r*=' +
                         str(np.int(rs)) + ', z*=' + str(np.int(zs)) +
                         ', res=' + str(np.round(res, 2)))
                ax3_.plot(rs,
                          pe / PE_ref,
                          'o',
                          color=cm(res * 10),
                          label='s=' + str(np.round(s, 1)) + ', r*=' +
                          str(np.int(rs)) + ', z*=' + str(np.int(zs)) +
                          ', res=' + str(np.round(res, 2)))
                print('........', zs, rs)
                a1.plot(rs,
                        zs,
                        'o',
                        color=cm(res * 10),
                        label='s=' + str(np.round(s, 1)) + ', r*=' +
                        str(np.int(rs)) + ', z*=' + str(np.int(zs)) +
                        ', res=' + str(np.round(res, 2)))

        fsize = 15
        ax1.set_xlabel('z*   [m]', fontsize=fsize)
        ax2.set_xlabel('z*   [m]', fontsize=fsize)
        ax3.set_xlabel('z*   [m]', fontsize=fsize)
        ax1.set_ylabel('PE(z*)   [J]', fontsize=fsize)
        ax2.set_ylabel('PE(z*)/PE_ref', fontsize=fsize)
        ax3.set_ylabel('PE(z*)/PE_ref', fontsize=fsize)
        ax1.set_ylim(
            np.amin(scaling) * .8 * PE_ref,
            np.amax(scaling) * 1.15 * PE_ref)
        ax2.set_ylim(np.amin(scaling) * .8, np.amax(scaling) + 1)
        ax3.set_ylim(np.amin(scaling) * .8, np.amax(scaling) + 1)
        ax1.set_xlim(zstar_min * .9, zstar_max)
        ax2.set_xlim(zstar_min * .9, zstar_max)
        ax3.set_xlim(zstar_min * .9, zstar_max)
        ax1.set_xticks(zstar_range, minor=True)
        ax2.set_xticks(zstar_range, minor=True)
        ax2.set_yticks(np.arange(0, np.amax(scaling) + 1), minor=True)
        ax3.set_yticks(np.arange(0, np.amax(scaling) + 1), minor=True)
        ax1.grid(which='major', axis='x', linestyle='-', alpha=0.6)
        ax1.grid(which='minor', axis='x', linestyle='-', alpha=0.2)
        ax1.grid(which='major', axis='y', linestyle='-', alpha=0.6)
        ax2.grid(which='major', axis='x', linestyle='-', alpha=0.6)
        ax2.grid(which='minor', axis='x', linestyle='-', alpha=0.2)
        ax2.grid(which='both', axis='y', linestyle='-', alpha=0.6)
        ax3.grid(which='major', axis='x', linestyle='-', alpha=0.6)
        ax3.grid(which='minor', axis='x', linestyle='-', alpha=0.2)
        ax3.grid(which='both', axis='y', linestyle='-', alpha=0.6)
        # ax2.legend(loc='center left', bbox_to_anchor=(1., 0.5), fontsize=9) # for two plots
        ax2.legend(loc='center left', bbox_to_anchor=(-1.65, 0.5), fontsize=9)
        ax3.legend(loc='center left', bbox_to_anchor=(1., .5),
                   fontsize=9)  #, ncol=2)
        ax1.set_title('error bars: 5%, 10%')
        ax2.set_title('error bars: 0.1*PE_ref')
        ax3.set_title('error bars: 0.1*PE_ref')
        fig1.suptitle('PE_ref=PE(z*=' + str(zstar_ref) + ',r*=' +
                      str(rstar_ref) + '), marg=' + str(marg) + 'm (dx=' +
                      str(dx) + 'm)',
                      fontsize=15)
        fig1.subplots_adjust(bottom=0.12,
                             right=.85,
                             left=0.1,
                             top=0.9,
                             wspace=0.2)
        fig1.savefig(
            os.path.join(
                path_out, 'PE_const_initialization_dTh' + str(dTh) + '_marg' +
                str(np.int(marg)) + 'm_dx' + str(dx) + 'm_zstar.pdf'))
        plt.close(fig1)

        ax1_.set_xlabel('r*   [m]', fontsize=fsize)
        ax2_.set_xlabel('r*   [m]', fontsize=fsize)
        ax3_.set_xlabel('r*   [m]', fontsize=fsize)
        ax1_.set_ylabel('PE(dTh)   [J]', fontsize=fsize)
        ax2_.set_ylabel('PE(dTh)/PE_ref', fontsize=fsize)
        ax3_.set_ylabel('PE(dTh)/PE_ref', fontsize=fsize)
        ax1_.set_ylim(np.amin(scaling) * .8, np.amax(scaling) * 1.15 * PE_ref)
        ax2_.set_ylim(np.amin(scaling) * .8, np.amax(scaling) + 1)
        ax3_.set_ylim(np.amin(scaling) * .8, np.amax(scaling) + 1)
        ax1_.set_xlim(rstar_min * .9, rstar_max)
        ax2_.set_xlim(rstar_min * .9, rstar_max)
        ax3_.set_xlim(rstar_min * .9, rstar_max)
        ax1_.set_xticks(rstar_range, minor=True)
        ax2_.set_xticks(rstar_range, minor=True)
        ax2_.set_yticks(np.arange(0, np.amax(scaling) + 1), minor=True)
        ax3_.set_yticks(np.arange(0, np.amax(scaling) + 1), minor=True)
        ax1_.grid(which='major', axis='x', linestyle='-', alpha=0.6)
        ax1_.grid(which='minor', axis='x', linestyle='-', alpha=0.2)
        ax1_.grid(which='major', axis='y', linestyle='-', alpha=0.6)
        ax2_.grid(which='major', axis='x', linestyle='-', alpha=0.6)
        ax2_.grid(which='minor', axis='x', linestyle='-', alpha=0.2)
        ax2_.grid(which='both', axis='y', linestyle='-', alpha=0.6)
        ax3_.grid(which='major', axis='x', linestyle='-', alpha=0.6)
        ax3_.grid(which='minor', axis='x', linestyle='-', alpha=0.2)
        ax3_.grid(which='both', axis='y', linestyle='-', alpha=0.6)
        # ax2.legend(loc='center left', bbox_to_anchor=(1., 0.5), fontsize=9) # for two plots
        ax2_.legend(loc='center left', bbox_to_anchor=(-1.65, 0.5), fontsize=9)
        ax3_.legend(loc='center left', bbox_to_anchor=(1., .5),
                    fontsize=9)  # , ncol=2)
        ax1_.set_title('error bars: 5%, 10%')
        ax2_.set_title('error bars: 0.1*PE_ref')
        ax3_.set_title('error bars: 0.1*PE_ref')
        fig2.suptitle('PE_ref=PE(z*=' + str(zstar_ref) + ',r*=' +
                      str(rstar_ref) + '), marg=' + str(marg) + 'm (dx=' +
                      str(dx) + 'm)',
                      fontsize=15)
        fig2.subplots_adjust(bottom=0.12,
                             right=.8,
                             left=0.1,
                             top=0.9,
                             wspace=0.2)
        fig2.savefig(
            os.path.join(
                path_out, 'PE_const_initialization_dTh' + str(dTh) + '_marg' +
                str(np.int(marg)) + 'm_dx' + str(dx) + 'm_rstar.pdf'))
        plt.close(fig2)

        a1.set_xlim(rstar_min * .9, rstar_max * 1.1)
        a1.set_ylim(zstar_min * .9, zstar_max * 1.1)
        a2.set_xlim(rstar_min * .9, rstar_max)
        a2.set_ylim(np.amin(scaling) * .5, np.amax(scaling) * 1.5)
        a1.set_xlabel('r*   [m]', fontsize=fsize)
        a1.set_ylabel('z*   [m]', fontsize=fsize)
        a2.set_xlabel('r*   [m]', fontsize=fsize)
        a2.set_ylabel('PE(dTh)/PE_ref', fontsize=fsize)
        a1.grid(which='major', axis='x', linestyle='-', alpha=0.6)
        a1.grid(which='minor', axis='x', linestyle='-', alpha=0.2)
        a1.grid(which='both', axis='y', linestyle='-', alpha=0.6)
        a2.grid(which='major', axis='x', linestyle='-', alpha=0.6)
        a2.grid(which='minor', axis='x', linestyle='-', alpha=0.2)
        a2.grid(which='both', axis='y', linestyle='-', alpha=0.6)
        a1.legend(loc='center left', bbox_to_anchor=(-.6, 0.5), fontsize=9)
        a2.legend(loc='center left', bbox_to_anchor=(1.06, 0.5), fontsize=9)
        fig3.subplots_adjust(bottom=0.12,
                             right=.87,
                             left=0.2,
                             top=0.9,
                             wspace=0.2)
        fig3.savefig(
            os.path.join(
                path_out, 'PE_const_initialization_dTh' + str(dTh) + '_marg' +
                str(np.int(marg)) + 'm_dx' + str(dx) + 'm.pdf'))
        plt.close(fig3)

        print('')
        print('scaling: ', scaling)
        s = 1
        i = np.where(np.asarray(scaling) == s)[0][0]
        print('s=' + str(s) + ' (i=' + str(i) + ')')
        for j in range(1, np.int(count[i])):
            pe = params_dict[str(s)][j, 0]
            zs = params_dict[str(s)][j, 1]
            rs = params_dict[str(s)][j, 2]
            res = params_dict[str(s)][j, 3]
            print('r*=' + str(np.int(rs)) + ', z*=' + str(np.int(zs)) +
                  ', res=' + str(np.round(res, 2)))

        file_name = 'PE_scaling_dTh' + str(dTh) + '_marg' + str(
            np.int(marg)) + 'm_dx' + str(dx) + 'm.nc'
        dump_file(file_name, dTh_range, zstar_range, rstar_range, PE_ref,
                  scaling, PE_range, PE, params_dict, count, path_out)

    # print('')
    # for iTh, dTh in enumerate(dTh_range):
    #     print('dTh='+str(dTh) + ': z*='+str(zstar_range))
    #     print('r*=' +str(diff[1, iTh, :]))
    #     print('PE_ref - PE=' +str(diff[2, iTh, :]))
    #     print('PE/PE_ref = '+str(diff[2, iTh, :]/PE_ref))

    return
def main():
    parser = argparse.ArgumentParser(prog='LES_CP')
    args = parser.parse_args()

    res = 25
    run = 'run4'
    dTh = 3
    rstar = 1000
    zstar = 1000
    case = 'dTh' + str(dTh) + '_z' + str(zstar) + '_r' + str(rstar)
    # case_name = args.casename
    case_name = 'ColdPoolDry_single_3D'

    path_root = '/nbi/ac/cond1/meyerbe/ColdPools/3D_sfc_fluxes_off/single_3D_noise/'
    path = os.path.join(path_root, run + '_dx' + str(res) + 'm', case)
    path_fields = os.path.join(path, 'fields')
    # path_out_figs = '/nbi/ac/cond1/meyerbe/paper_CP_single'
    path_out_figs = '/nbi/ac/cond1/meyerbe/paper_CP'
    # path_out_figs = '/nbi/home/meyerbe/paper_CP'
    print('path figures: ' + path_out_figs)

    nml = simplejson.loads(open(os.path.join(path, case_name + '.in')).read())
    ic = nml['init']['ic']
    jc = nml['init']['jc']
    nx = nml['grid']['nx']
    ny = nml['grid']['ny']
    dx = np.ndarray(3, dtype=np.int)
    dx[0] = nml['grid']['dx']
    dx[1] = nml['grid']['dy']
    dx[2] = nml['grid']['dz']
    kmax = np.int(1.0e3 / dx[2])
    print('res: ' + str(dx))
    print('CP centre: ' + str(ic) + ', ' + str(jc))
    print('')

    print('read in vorticity')
    # root_vort = nc.Dataset(os.path.join(path, 'fields_vorticity/field_vort_xz.nc'))
    # time_vort = root_vort.groups['fields'].variables['time'][:]
    # vorticity_ = root_vort.groups['fields'].variables['vort_xz'][:, :, :kmax]
    # root_vort.close()
    root_vort = nc.Dataset(
        os.path.join(path, 'fields_vorticity/field_vort_yz.nc'))
    time_vort = root_vort.groups['fields'].variables['time'][:]
    vorticity_ = root_vort.groups['fields'].variables['vort_yz'][:, :, :kmax]
    root_vort.close()

    print('read in azimuthally averaged fields')
    root_vrad_2D = nc.Dataset(os.path.join(path, 'fields_v_rad/v_rad.nc'))
    # time_rad = root_vrad_2D.variables['time'][:]
    vrad_2D = root_vrad_2D.variables['v_rad'][:, :, jc, :kmax]
    root_vrad_2D.close()
    root_vrad = nc.Dataset(
        os.path.join(path, 'data_analysis/stats_radial_averaged.nc'))
    time_rad = root_vrad.groups['timeseries'].variables['time'][:]
    v_rad = root_vrad.groups['stats'].variables['v_rad'][:, :, :kmax]
    w_rad = root_vrad.groups['stats'].variables['w'][:, :, :kmax]
    s_rad = root_vrad.groups['stats'].variables['s'][:, :, :kmax]
    root_vrad.close()
    theta_rad = thetas_c(s_rad, 0.0)
    del s_rad
    root_vort_rad = nc.Dataset(
        os.path.join(path, 'fields_vorticity', 'field_vort_phi.nc'))
    vort_rad = root_vort_rad.groups['fields'].variables['vort_phi'][:, :, :]
    root_vort_rad.close()
    print('')
    print('dimensions: ', w_rad.shape, vort_rad.shape)
    print('')

    jmin_range = [150, 100, 100]
    for i, t0 in enumerate([900, 1200, 1500]):
        it = t0 / 100
        # print('')
        print('time: ', t0)
        # print('')
        jmin = jmin_range[i]
        jmax = ny - jmin
        rmax = np.int(.5 * (jmax - jmin))
        fullpath_in = os.path.join(path_fields, str(t0) + '.nc')
        root_field = nc.Dataset(fullpath_in)
        grp = root_field.groups['fields']
        s = grp.variables['s'][ic, :, :kmax]
        w = grp.variables['w'][ic, :, :kmax]
        # v = grp.variables['v'][ic,:,:kmax]
        u = grp.variables['u'][ic, :, :kmax]
        root_field.close()
        theta = thetas_c(s, 0.0)[ic - nx / 2:ic + nx / 2, :]
        vorticity = vorticity_[np.int(t0 / 100), :, :]

        # fig_name = 'CP_structure_rad_dx' + str(res) + '_' + case + '_t'+str(t0)+'_test.png'
        # plot_test(theta, theta_rad, u, v_rad, w, w_rad, vorticity, vort_rad,
        #       it, jmin, jmax, rmax, kmax, dx, nx, ny,
        #       fig_name, path_out_figs)
        fig_name = 'CP_structure_rad_dx' + str(res) + '_' + case + '_t' + str(
            t0) + '.png'
        print(fig_name)
        plot_figure_rad(theta, theta_rad, u, v_rad, w, w_rad, vorticity,
                        vort_rad, it, jmin, jmax, rmax, kmax, dx, nx, ny,
                        fig_name, path_out_figs)

    return
Esempio n. 7
0
def main():
    parser = argparse.ArgumentParser(prog='LES_CP')
    # parser.add_argument("--tmin")
    # parser.add_argument("--tmax")
    # parser.add_argument("--dx")
    # parser.add_argument("--shift")
    # parser.add_argument("--irmax")
    # parser.add_argument("--nsub")
    args = parser.parse_args()

    res = 25
    run = 'run4'
    dTh = 3
    rstar = 1000
    zstar = 1000
    case = 'dTh' + str(dTh) + '_z' + str(zstar) + '_r' + str(rstar)
    # case_name = args.casename
    case_name = 'ColdPoolDry_single_3D'

    # time_range = [600, 900, 1200, 1500]
    time_range = [600, 1200, 1800, 2400]
    nt = len(time_range)
    imin = 40
    k0 = 0

    path_root = '/nbi/ac/cond1/meyerbe/ColdPools/3D_sfc_fluxes_off/single_3D_noise/'
    path = os.path.join(path_root, run + '_dx' + str(res) + 'm', case)
    print(path)
    path_fields = os.path.join(path, 'fields')
    path_out_figs = '/nbi/home/meyerbe/paper_CP/figs_run4'
    if not os.path.exists(path_out_figs):
        os.mkdir(path_out_figs)

    nml = simplejson.loads(open(os.path.join(path, case_name + '.in')).read())
    ic = nml['init']['ic']
    jc = nml['init']['jc']
    nx = nml['grid']['nx']
    ny = nml['grid']['ny']
    dx = np.ndarray(3, dtype=np.int)
    dx[0] = nml['grid']['dx']
    dx[1] = nml['grid']['dy']
    dx[2] = nml['grid']['dz']
    # kmax = np.int(1.0e3 / dx[2])
    dt_fields = nml['fields_io']['frequency']
    print('res: ' + str(dx))
    print('CP centre: ' + str(ic) + ', ' + str(jc))
    print('')
    ''' radial velocity '''
    root_vrad_2D = nc.Dataset(os.path.join(path, 'fields_v_rad/v_rad.nc'))
    # time_rad = root_vrad_2D.variables['time'][:]
    vrad_2D_ = root_vrad_2D.variables['v_rad'][:, :, :,
                                               k0]  # v_rad[nt,nx,ny,nz]
    root_vrad_2D.close()
    # root_vrad = nc.Dataset(os.path.join(path, 'data_analysis/stats_radial_averaged.nc'))
    # time_rad = root_vrad.groups['timeseries'].variables['time'][:]
    # vrad = root_vrad.groups['stats'].variables['v_rad'][:, :, k0]         # v_rad[nt,nr,nz]
    # root_vrad.close()

    # ''' vorticity '''
    # root_vort = nc.Dataset(os.path.join(path, 'fields_vorticity/field_vort_yz.nc'))
    # time_vort = root_vort.groups['fields'].variables['time'][:]
    # vorticity_ = root_vort.groups['fields'].variables['vort_yz'][:, :, :kmax]     # vort_yz[t,y,z]
    # root_vort.close()
    ''' Figure with potential temperature, vertical velocity, radial velocity ? '''
    # zoom in to see clefts

    fig_name = 'CP_crosssection_dx' + str(res) + '_' + case + '.png'
    # nlev = 2e2
    nlev = 2e1
    ncol = len(time_range)
    nrow = 3
    axins_x = .594
    axins_width = .13
    textprops = dict(facecolor='white', alpha=0.9, linewidth=0.)
    t_pos_x = 85.
    t_pos_y = 85.

    fig, axes = plt.subplots(nrow,
                             ncol,
                             figsize=(4.9 * ncol, 5 * nrow),
                             sharex='all',
                             sharey='all')

    lvls_th = np.linspace(298, 300, nlev)
    lvls_w = np.linspace(-3, 3, nlev)
    lvls_vrad = np.linspace(-3, 3, nlev)

    for i, t0 in enumerate(time_range):
        #if i < 2:
        #    continue
        it = np.int(t0 / dt_fields)
        print('time: ', t0)

        fullpath_in = os.path.join(path_fields, str(t0) + '.nc')
        root_field = nc.Dataset(fullpath_in)
        grp = root_field.groups['fields']
        s = grp.variables['s'][:, :, k0]
        w = grp.variables['w'][:, :, k0]
        # v = grp.variables['v'][:,:,k0]
        # u = grp.variables['u'][:, :, k0]
        root_field.close()
        theta = thetas_c(s, 0.0)  #[ic - nx / 2:ic + nx / 2, :]
        # vorticity = vorticity_[it, :, :]
        vrad_2D = vrad_2D_[it, :, :]

        axs = axes[0, :]
        cf = axs[i].contourf(theta[:, :].T,
                             levels=lvls_th,
                             cmap=cm_bw_r,
                             extend='min')
        if t0 == time_range[-2]:
            # plt.colorbar(cf, ax=axs[i], shrink=0.8)
            axins = plt.axes([axins_x, 0.815, axins_width, axins_width])
            axins.contourf(theta[ic + 48:, jc + 48:].T,
                           levels=lvls_th,
                           cmap=cm_bw_r)
            axins.set_aspect('equal')
            axins.set_xlim(0, 280)
            axins.set_ylim(0, 280)
            axins.set_xticklabels('')
            axins.set_yticklabels('')
            #axins = ax[i].inset_axes([0.5, 0.5, 0.47, 0.47])
            ## axins.imshow(theta[ic:,jc:], extent=extent, interpolation="nearest", origin="lower")
            #axins.contourf(theta[ic:,jc:].T, levels=lvls_th, cmap=cm_bw_r, extend='min')
        if t0 == time_range[-1]:
            cax = plt.axes([0.95, 0.7, 0.012, 0.22])
            plt.colorbar(cf, cax=cax, ticks=np.arange(298, 300.1, 1))

        axs = axes[1, :]
        cf = axs[i].contourf(w[:, :].T,
                             levels=lvls_w,
                             cmap=cm_bwr,
                             extend='both')
        if t0 == time_range[-2]:
            axins = plt.axes([axins_x, 0.495, axins_width, axins_width])
            axins.contourf(w[ic + 48:, jc + 48:].T, levels=lvls_w, cmap=cm_bwr)
            axins.set_aspect('equal')
            axins.set_xlim(0, 280)
            axins.set_ylim(0, 280)
            axins.set_xticklabels('')
            axins.set_yticklabels('')
        if t0 == time_range[-1]:
            cax = plt.axes([0.95, 0.38, 0.012, 0.22])
            cbar = plt.colorbar(cf, cax=cax, ticks=np.arange(-3, 3 + 0.02, 1.))

        axs = axes[2, :]
        cf = axs[i].contourf(vrad_2D[:, :].T,
                             levels=lvls_vrad,
                             cmap=cm_bwr,
                             extend='max')
        if t0 == time_range[-2]:
            axins = plt.axes([axins_x, 0.175, axins_width, axins_width])
            axins.contourf(vrad_2D[ic + 48:, jc + 48:].T,
                           levels=lvls_vrad,
                           cmap=cm_bwr)
            axins.set_aspect('equal')
            axins.set_xlim(0, 280)
            axins.set_ylim(0, 280)
            axins.set_xticklabels('')
            axins.set_yticklabels('')
        if t0 == time_range[-1]:
            cax = plt.axes([0.95, 0.06, 0.012, 0.22])
            cbar = plt.colorbar(cf, cax=cax, ticks=np.arange(0, 3.1, 1))

        for ax in axes[:, i].flat:
            ax.text(t_pos_x,
                    t_pos_y,
                    't=' + str(np.int(t0 / 60)) + 'min',
                    fontsize=16,
                    horizontalalignment='left',
                    bbox=textprops)

    #for ax in axes_[:,2].flat:
    #    ax.plot(ic,jc, 'ko', markersize=10)

    for ax in axes.flat:
        ax.set_xlim(imin, nx - imin)
        ax.set_ylim(imin, ny - imin)
        ax.set_aspect('equal')
        x_ticks = [np.int(n * dx[0] * 1e-3) for n in ax.get_xticks()]
        x_ticks = [np.int((n - imin) * dx[0] * 1e-3) for n in ax.get_xticks()]
        # x_ticks = [np.int((n-imin)) for n in ax.get_xticks()]
        #x_ticks = [np.int(n) for n in ax.get_xticks()]
        ax.set_xticklabels(x_ticks)
        y_ticks = [np.int(n * dx[1] * 1e-3) for n in ax.get_yticks()]
        y_ticks = [np.int((n - imin) * dx[0] * 1e-3) for n in ax.get_yticks()]
        # y_ticks = [np.int((n)) for n in ax.get_yticks()]
        #y_ticks = [np.int(n) for n in ax.get_yticks()]

        #ax.set_xticks(np.arange(0, (nx-2*imin)*dx[0], step=1.e3))
        # ax.set_xticks(np.arange(0, (nx-2*imin)))
        for label in ax.xaxis.get_ticklabels()[0::2]:
            label.set_visible(False)
        for label in ax.yaxis.get_ticklabels()[0::2]:
            label.set_visible(False)
        ax.set_yticklabels(y_ticks)
    for ax in axes[2, :].flat:
        ax.set_xlabel('x  [km]')
    for ax in axes[:, 0].flat:
        ax.set_ylabel('y  [km]')

    textprops = dict(facecolor='white', alpha=0.9, linewidth=0.)
    title_pos_x = imin + -120
    title_pos_y = ny - imin + 25
    title_font = 21
    txt = 'a) potential temperature'
    axes[0, 0].text(title_pos_x,
                    title_pos_y,
                    txt,
                    fontsize=title_font,
                    horizontalalignment='left',
                    bbox=textprops)
    txt = 'b) vertical velocity'
    axes[1, 0].text(title_pos_x,
                    title_pos_y,
                    txt,
                    fontsize=title_font,
                    horizontalalignment='left',
                    bbox=textprops)
    txt = 'c) radial velocity'
    axes[2, 0].text(title_pos_x,
                    title_pos_y,
                    txt,
                    fontsize=title_font,
                    horizontalalignment='left',
                    bbox=textprops)

    # axes[-1].legend(loc='upper center', bbox_to_anchor=(1.2, 1.),
    #                 fancybox=True, shadow=True, ncol=1, fontsize=10)
    plt.subplots_adjust(bottom=0.04,
                        right=.94,
                        left=0.05,
                        top=0.95,
                        wspace=0.08,
                        hspace=0.18)
    print('saving: ', os.path.join(path_out_figs, fig_name))
    fig.savefig(os.path.join(path_out_figs, fig_name))
    plt.close(fig)

    return
Esempio n. 8
0
def main():
    cm_rain = plt.cm.get_cmap('rainbow')
    cm_rep = plt.cm.get_cmap('prism')
    cm = cm_rain

    parser = argparse.ArgumentParser(prog='LES_CP')
    parser.add_argument("--dx")
    parser.add_argument("--dTh_min")
    parser.add_argument("--dTh_max")
    args = parser.parse_args()

    path_out = './figs_Initialization/'

    'surface values'
    Th_g = 300.0  # temperature for neutrally stratified background (value from Soares Surface)
    if args.dx:
        dx_ = np.int(args.dx)
    else:
        dx_ = 50
    marg = 200.
    z_half = define_geometry(dx_, marg)
    set_parameters()
    print('dx: ' + str(dx_))
    ''' Parameter range '''
    if args.dTh_min:
        dTh_min = np.int(args.dTh_min)
    else:
        dTh_min = 2
    if args.dTh_max:
        dTh_max = np.int(args.dTh_max)
    else:
        dTh_max = 4
    dTh_range = np.arange(dTh_min, dTh_max + 1)
    dTh_range = [2, 3, 4]
    # for dx=100m, no matches for r*>4200m;
    # for dx=50m, matches for r*=..., 3600, 4900, 5000; no matches for r<400m
    rstar_min = 5e2
    rstar_max = 25e2
    zstar_min = 5e2
    zstar_max = 25e2
    rstar_range = np.arange(rstar_min, rstar_max + 100, 100)
    zstar_range = np.arange(zstar_min, zstar_max + 100, 1e2)
    n_thermo = len(dTh_range)
    n_geom_z = len(zstar_range)
    n_geom_r = len(rstar_range)
    print('dTh: ' + str(dTh_range))
    print('zstar: ' + str(zstar_range))
    print('rstar: ' + str(rstar_range))
    print('n_geom_z: ' + str(n_geom_z))
    print('n_geom_r: ' + str(n_geom_r))
    ''' PE scaling-range '''
    # scaling = [2**(-1), 2**0, 2**1, 2**2, 2**3]
    scaling = [2**0]
    print('scaling: ' + str(scaling))
    print('')
    ''' Reference case '''
    dTh_ref = 3
    rstar_ref = 1000
    zstar_ref = 1000
    if dx_ == 100:
        path_ref = '/nbi/ac/cond1/meyerbe/ColdPools/3D_sfc_fluxes_off/single_3D_noise/run2_dx100m/dTh3_z1000_r1000/'
    elif dx_ == 50:
        path_ref = '/nbi/ac/cond1/meyerbe/ColdPools/3D_sfc_fluxes_off/single_3D_noise/run3_dx50m/dTh3_z1000_r1000_nz240/'
    case_name = 'ColdPoolDry_single_3D'
    print('Reference case: ' + path_ref)
    rootgrp = nc.Dataset(
        os.path.join(path_ref, 'stats', 'Stats.' + case_name + '.nc'))
    rho0_stats = rootgrp.groups['reference'].variables['rho0'][:]
    # alpha0_stats = rootgrp.groups['reference'].variables['alpha0'][:]
    zhalf_stats = rootgrp.groups['reference'].variables['z'][:]
    # rho_unit = rootgrp.groups['reference'].variables['rho0'].units
    rootgrp.close()
    print('')
    print('z-arrays:')
    print('z_half:', z_half[:20])
    print('z_half_stats:', zhalf_stats[:20])
    print('')
    ''' reference PE '''
    print('Reference case: ')
    z_max_arr, theta_z = compute_envelope(dTh_ref, Th_g, rstar_ref, zstar_ref,
                                          marg, z_half)
    PE_ref = compute_PE(theta_z, Th_g, zstar_ref, rho0_stats, zhalf_stats,
                        z_half)
    PE_ref_approx = compute_PE_density_approx(dTh_ref, zstar_ref, rstar_ref,
                                              z_half)
    print('PE_ref: ', PE_ref)
    # test reference numerically
    rootgrp_field = nc.Dataset(os.path.join(path_ref, 'fields', '0.nc'))
    s0 = rootgrp_field.groups['fields'].variables['s'][:, :, :]
    rootgrp_field.close()
    ic_ = s0.shape[0] / 2
    jc_ = s0.shape[1] / 2
    theta = thetas_c(s0, 0.0)[ic_ - nx / 2:ic_ + nx / 2,
                              jc_ - ny / 2:jc_ + ny / 2, :nz]
    PE_ref_num = compute_PE(theta, Th_g, zstar_ref, rho0_stats, zhalf_stats,
                            z_half)
    del s0
    print('  (from envel.) PE_ref =        ' + str(PE_ref))
    print('  (from field)  PE_ref_num =    ' + str(PE_ref_num))
    print('   difference: ' + str((PE_ref - PE_ref_num) / PE_ref))
    print('')
    # print('   (upper limit)  PE_up = ' + str(PE_ref_up))
    # print('   (lower limit)  PE_low = ' + str(PE_ref_low))
    # print('   difference: '+str((PE_ref-PE_ref_up)/PE_ref))
    # print('   difference: '+str((PE_ref-PE_ref_low)/PE_ref))
    print('')

    for iTh, dTh in enumerate(dTh_range):
        rstar_guess = np.sqrt(PE_ref_approx / (dTh * zstar_max**2))
        rstar_min = rstar_guess - dx
        rstar_max = np.minimum(
            np.sqrt(PE_ref_approx / (dTh * zstar_min**2)) + 2 * dx, 2500)
        print('rstar', rstar_guess, rstar_min, rstar_max)
        print('')
        rstar_range = dx * np.arange(np.floor(rstar_min / dx),
                                     np.ceil(rstar_max / dx) + 1)
        n_geom_r = len(rstar_range)
        PE = np.zeros((n_geom_z, n_geom_r))
        diff = np.zeros((3, n_thermo, n_geom_z))
        diff[2, :, :] = 2 * PE_ref * np.ones((n_thermo, n_geom_z))

        print('dTh: ', dTh, 'r*-range', rstar_range)
        fig1, (ax1, ax2) = plt.subplots(1, 2, figsize=(11, 5))
        ax2.fill_between([rstar_range[0], rstar_range[-1]],
                         0.9,
                         1.1,
                         color='gray',
                         alpha=0.2)
        ax2.fill_between([rstar_range[0], rstar_range[-1]],
                         0.95,
                         1.05,
                         color='gray',
                         alpha=0.4)

        for iz, zstar in enumerate(zstar_range):
            PE_guess = 0.0
            for ir, rstar in enumerate(rstar_range):
                print('z*: ', zstar, 'r*:', rstar)

                z_max_arr, theta = compute_envelope(dTh, rstar, zstar, Th_g)
                PE[iz, ir] = compute_PE(theta, Th_g, z_max_arr, zstar,
                                        rho0_stats, zhalf_stats)

                diff_aux = np.abs(PE[iz, ir] - PE_ref)
                if diff_aux < np.abs(diff[2, iTh, iz] - PE_ref):
                    diff[0, iTh, iz] = ir
                    diff[1, iTh, iz] = rstar
                    diff[2, iTh, iz] = PE[iz, ir]

                rstar_guess = np.sqrt(PE_ref_approx / (dTh * zstar**2))
                if rstar == rstar_guess:
                    PE_guess = PE[iz, ir]

            ax1.plot(rstar_range,
                     PE[iz, :],
                     '-o',
                     color=cm(np.double(iz) / n_geom_z))
            ax2.plot(
                rstar_range,
                PE[iz, :] / PE_ref,
                '-o',
                color=cm(np.double(iz) / n_geom_z),
                # label='dTh='+str(dTh)+', z*='+str(zstar)+', r*='+str(diff[1, iTh, iz])
                #       + ', (PE/PE_ref='+str(diff[2, iTh, iz]) + ')')
                label='z*=' + str(zstar) + ', r*=' + str(diff[1, iTh, iz]) +
                ', (PE/PE_ref=' + str(np.round(diff[2, iTh, iz] / PE_ref, 2)) +
                ')')
            ax1.plot(diff[1, iTh, iz], PE[iz, diff[0, iTh, iz]], 'ko')
            ax2.plot(diff[1, iTh, iz], PE[iz, diff[0, iTh, iz]] / PE_ref, 'ko')
            ax1.plot(rstar_guess, PE_guess, 'kd')
            ax2.plot(rstar_guess, PE_guess / PE_ref, 'dk')
        ax1.plot([rstar_range[0], rstar_range[-1]], [PE_ref, PE_ref],
                 '-k',
                 linewidth=2,
                 label='PE ref (dTh=' + str(dTh_ref) + ', z*=' +
                 str(zstar_ref) + ', ' + 'r*=' + str(rstar_ref) + ')')
        ax2.plot([rstar_range[0], rstar_range[-1]], [1., 1.],
                 '-k',
                 linewidth=2)

        ax1.set_xlabel('r*   [m]')
        ax2.set_xlabel('r*   [m]')
        ax1.set_ylabel('PE(r*)   [J]')
        ax2.set_ylabel('PE(r*)/PE_ref')
        ax1.set_xlim(rstar_range[0], diff[1, iTh, 0] + 2 * dx)
        ax1.set_ylim(np.amin(PE), PE_ref * 1.3)
        ax2.set_xlim(rstar_range[0], diff[1, iTh, 0] + 2 * dx)
        ax2.set_ylim(0.5, 1.5)
        ax2.legend(loc='center left', bbox_to_anchor=(1., 0.5), fontsize=8)
        plt.suptitle('dTh=' + str(dTh) + ', marg=' + str(marg) + 'm',
                     fontsize=15)
        plt.subplots_adjust(bottom=0.12,
                            right=.75,
                            left=0.07,
                            top=0.9,
                            wspace=0.25)
        fig1.savefig(
            os.path.join(
                path_out, 'initialization_dTh' + str(dTh) + 'K_marg' +
                str(marg) + 'm.png'))
        plt.close(fig1)

        fig, (ax1, ax2) = plt.subplots(1, 2, figsize=(11, 5))
        cf = ax1.contourf(PE[:, :])
        plt.colorbar(cf, ax=ax1)
        ax1.set_title('PE(z*,r*)')
        ax1.set_xlabel('z*')
        ax1.set_ylabel('r*')
        lvls = np.linspace(0, 2, 1e3)
        cf = ax2.contourf(PE[:, :] / PE_ref, levels=lvls, extend='max')
        plt.colorbar(cf, ax=ax2)
        ax2.set_title('PE(z*,r*)/PE(1000m, 1000m)')
        ax2.set_xlabel('z*')
        ax2.set_ylabel('r*')
        plt.savefig(
            os.path.join(
                path_out, 'initialization_dTh' + str(dTh) + 'K_marg' +
                str(marg) + 'm_contourf.png'))
        plt.close(fig)

        file_name = 'PE_init_dTh' + str(dTh) + 'K_marg' + str(marg) + 'm.nc'
        dump_file(file_name, n_geom_z, n_geom_r, zstar_range, rstar_range, PE,
                  PE_ref, path_out)

    print('')
    for iTh, dTh in enumerate(dTh_range):
        print('dTh=' + str(dTh) + ': z*=' + str(zstar_range))
        print('r*=' + str(diff[1, iTh, :]))
        print('PE_ref - PE=' + str(diff[2, iTh, :]))
        print('PE/PE_ref = ' + str(diff[2, iTh, :] / PE_ref))

    return
Esempio n. 9
0
def main():
    # Parse information from the command line
    parser = argparse.ArgumentParser(prog='LES_CP')
    parser.add_argument("casename")
    parser.add_argument("path")
    parser.add_argument("--times", nargs='+', type=int)
    parser.add_argument("--kmin")
    parser.add_argument("--kmax")
    parser.add_argument("--imin")
    parser.add_argument("--imax")
    args = parser.parse_args()

    global cm_bwr
    cm_bwr = plt.cm.get_cmap('bwr')

    files, times, nml = set_input_parameters(args)
    # configuration (defined in define_geometry)
    # ic1 = ic - r_int; ic2 = ic1; ic3 = ic + (a - r_int)
    # jc1 = jc - idhalf; jc2 = jc + idhalf; jc3 = jc
    print('')
    ID = os.path.split(path_in)[1]
    if ID == '':
        ID = os.path.basename(path_in[:-1])
    print('id: ', ID)
    i0_coll, j0_coll, ic_arr, jc_arr, d, x_half, y_half, z_half = define_geometry(
        case_name, nml, files)

    if args.times:
        time_range = [np.int(t) for t in args.times]
    else:
        if d == 12000:
            time_range = [600, 1200, 1500, 1800, 2000]
        elif d == 15000:
            time_range = [600, 1100, 1200, 1300, 1500]
        # time_range = [600, 1100]
    dj = (jc_arr[1] - jc_arr[0])  # side length of triangle
    h = (ic_arr[2] - ic_arr[0])  # height of triangle
    dplot = 1.7 * dj
    di = (dplot - h) / 2
    print('distance: ' + str(d))
    print('geometry: x=' + str(ic_arr) + ', y=' + str(jc_arr))
    print('plotting: dplot', dplot)
    k0 = 0
    print('k0=' + str(k0))

    imin = np.int(i0_coll - 1. / 3 * h - di)
    imax = np.int(i0_coll + 2. / 3 * h + di)
    jmin = np.int(j0_coll - .5 * dplot)
    jmax = np.int(j0_coll + .5 * dplot)
    # x_arr = x_half[i0_coll - di:i0_coll + di + 1]
    # y_arr = y_half[j0_coll - dj:j0_coll + dj + 1]
    x_arr = x_half[:(imax - imin)]
    y_arr = y_half[:(jmax - jmin)]
    print('')

    print('')
    ''' --- call plotting functions --- '''
    print('')
    print('path Figures: ' + pathout_figs)

    cm_cont = plt.cm.get_cmap('gnuplot')
    cm_lines = plt.cm.get_cmap('winter')
    cbar_pos_x = .94
    cbar_width = .012
    cbar_height = .3

    fig_name = 'triple_casestudy.png'
    nrow = 2
    ncol = len(time_range)
    fig, axes = plt.subplots(nrow,
                             ncol,
                             figsize=(4.9 * ncol, 5 * nrow),
                             sharex='all',
                             sharey='all')
    for it, t0 in enumerate(time_range):
        ax0 = axes[0, it]
        ax1 = axes[1, it]
        file = str(t0) + '.nc'
        print('--- time: ', t0, '(' + str(it) + ') ---')
        vel_h = np.ndarray((2, imax - imin, jmax - jmin, kmax + 1))
        print(os.path.join(path_fields, file))

        print('')
        print('imin, etc', imin, imax, jmin, jmax)
        print('')

        root = nc.Dataset(os.path.join(path_fields, file), 'r')
        vel_h[0, :, :, :] = root.groups['fields'].variables['u'][
            imin:imax, jmin:jmax, :kmax + 1]
        vel_h[1, :, :, :] = root.groups['fields'].variables['v'][
            imin:imax, jmin:jmax, :kmax + 1]
        w = root.groups['fields'].variables['w'][imin:imax, jmin:jmax, k0]
        w_up = root.groups['fields'].variables['w'][imin:imax, jmin:jmax, 5]
        s = root.groups['fields'].variables['s'][imin:imax,
                                                 jmin:jmax, :kmax + 1]
        theta = thetas_c(s, 0.0)
        temp = root.groups['fields'].variables['temperature'][
            imin:imax, jmin:jmax, :kmax + 1]
        root.close()

        speed_h = np.sqrt(vel_h[0, :] * vel_h[0, :] +
                          vel_h[1, :] * vel_h[1, :])
        # t_mean = np.average(np.average(temp[:, :, :], axis=0), axis=0)
        # t_anomaly = temp[:, :, :] - t_mean
        if np.abs(speed_h[:, :, k0].max()) > 0.0:
            lw = 5 * speed_h[:, :, k0] / speed_h[:, :, k0].max()
        else:
            lw = 5 * np.ones(shape=speed_h[:, :, k0].shape)

        cm_cont_w = plt.cm.get_cmap('bwr')
        wmax = np.maximum(np.abs(np.amin(w)), np.abs(np.amax(w)))
        wmin = -wmax
        levels_w = np.linspace(wmin, wmax, 1e2)

        cm_cont_temp = plt.cm.get_cmap('gnuplot')
        tempmin = 298.
        tempmax = 300.
        levels_temp = np.linspace(tempmin, tempmax, 1e2)

        cf0 = ax0.contourf(x_arr,
                           y_arr,
                           w[:, :].T,
                           cmap=cm_cont_w,
                           levels=levels_w)  #, extend='min')
        # cf1 = ax1.contourf(x_arr, y_arr, temp[:, :, k0].T, cmap=cm_cont_temp, levels=levels_temp, extend='min')
        cf1 = ax1.contourf(x_arr,
                           y_arr,
                           theta[:, :, k0].T,
                           cmap=cm_cont_temp,
                           levels=levels_temp,
                           extend='min')

        # ax0.plot([x_arr[ic_arr[0]-imin], x_arr[ic_arr[1]-imin], x_arr[ic_arr[2]-imin]],
        #          [y_arr[jc_arr[0]-jmin], y_arr[jc_arr[1]-jmin], y_arr[jc_arr[2]-jmin]], 'o', markersize=12, color='k')
        # ax0.plot(x_arr[i0_coll-imin], y_arr[j0_coll-jmin], 'o', markersize=12, color='r')

        if it == ncol - 1:
            cax = plt.axes([cbar_pos_x, 0.55, cbar_width, cbar_height])
            cb = plt.colorbar(cf0,
                              cax=cax,
                              ticks=np.arange(np.floor(wmin),
                                              np.floor(wmax) + 1, 1))
            cb.set_label(r'w [m/s]', rotation=90)
            cb.ax.tick_params(width=1, size=4)  # , labelsize=6)
            cax = plt.axes([cbar_pos_x, 0.1, cbar_width, cbar_height])
            cb = plt.colorbar(cf1,
                              cax=cax,
                              ticks=np.arange(np.floor(tempmin),
                                              np.floor(tempmax) + .5, 1.))
            # text = cax.yaxis.label
            # font = plt.font_manager.FontProperties(family='times new roman', style='italic', size=16)
            # text.set_font_properties(font)
            cb.set_label(r'pot. temp. [K]', rotation=90)
            cb.ax.tick_params(width=1, size=4)  # , labelsize=6)

        # ax0.streamplot(x_arr, y_arr, vel_h[0,:,:,k0].T, vel_h[1,:,:,k0].T,
        #                 color='k', density=1., linewidth=lw[:, :].T)
        # ax0.contour(x_arr, y_arr, w_up[:, :].T, levels=np.arange(.5,5.1,.5))#, colors='k')
        ax0.contour(x_arr, y_arr, w_up[:, :].T,
                    levels=np.arange(.5, .9, .5))  #, colors='k')
        ax1.streamplot(x_arr,
                       y_arr,
                       vel_h[0, :, :, k0].T,
                       vel_h[1, :, :, k0].T,
                       color='k',
                       density=1.,
                       linewidth=lw[:, :].T)
        # ax1.streamplot(x_arr, y_arr, vel_h[0,:,:,k0].T, vel_h[1,:,:,k0].T,
        #                 color=speed_h[:,:,k0].T, cmap=cm_lines,
        #                 linewidth=lw[:, :].T)
        # cb = fig.colorbar(strm.lines, shrink=0.5, ticks=np.arange(0, np.amax(speed), 1), aspect=17)
        # cb.ax.tick_params(width=1, size=4)  # , labelsize=6)

        textstr = 't=' + str(t0) + 's'
        props = dict(boxstyle='round',
                     facecolor='white',
                     alpha=0.5,
                     edgecolor='white')
        ax0.text(0.1,
                 1.13,
                 textstr,
                 transform=ax0.transAxes,
                 fontsize=24,
                 verticalalignment='top',
                 bbox=props)

    for ax in axes.flat:
        ax.set_aspect('equal')
        ax.set_xlim(x_arr[0], x_arr[imax - imin - 1])
        ax.set_ylim(y_arr[0], y_arr[jmax - jmin - 1])
    for ax in axes[-1, :].flat:
        x_ticks = ax.get_xticks() * 1e-3
        ax.set_xticklabels(x_ticks)
    for ax in axes[:, 0].flat:
        y_ticks = ax.get_yticks() * 1e-3
        ax.set_yticklabels(y_ticks)
        ax.set_ylabel('')
    # lbls = ['a)']
    # for lbl,ax in enumerate(axes.flat):
    #     textstr = 't=' + str(t0) + 's'
    #     props = dict(boxstyle='round', facecolor='white', alpha=0.5, edgecolor='white')
    #     ax0.text(0.1, 1.13, textstr, transform=ax0.transAxes, fontsize=24,
    #              verticalalignment='top', bbox=props)

    plt.subplots_adjust(bottom=0.05,
                        right=.93,
                        left=0.03,
                        top=0.92,
                        wspace=0.08,
                        hspace=0.08)
    print('saving: ', os.path.join(pathout_figs, fig_name))
    fig.savefig(os.path.join(pathout_figs, fig_name))
    plt.close(fig)

    # ''' (a) xy-plane '''
    # for k0 in krange:
    #     print('-- k0=' + str(k0) + ' --')
    #     plot_streamplot_xy_collision(cont_var_name, cont_var[:,:,:kmax+1], vel_h, speed_h,
    #                                      x_half, y_half, ic_arr, jc_arr,
    #                                      i0_coll, di, j0_coll, dj, k0, t0, path_out)
    #     # plot_streamplot_xy_varythickness(cont_var_name, cont_var, vel_h,
    #     #                                  x_half, y_half, speed_h, k0, t0, path_out)

    return
Esempio n. 10
0
def figure_zoomedCP_wholeCPasinsert(vrad_2D_, vtan_2D_, time_range, dt_fields,
                                    nx, dx, imin, ic, jc, k0, path_fields,
                                    path_out_figs, fig_name):
    ncol = len(time_range)
    nrow = 3
    axins_x = [0.145, 0.372, .598, .825]
    axins_x = [0.144, 0.364, .585, .805]
    axins_y = [.830, .510, .190]
    axins_width = .13
    axins_xlim = [100, 180, 240, 280]
    textprops = dict(facecolor='white', alpha=0.9, linewidth=0.)
    t_pos_x = 10.
    t_pos_y = 298.
    t_labels = ['i)', 'ii)', 'iii)', 'iv)']
    imax = nx - imin
    #cbar_labels = ['[K]', '[m/s]', '[m/s]']
    cbar_pos_x = 0.93

    fig, axes_ = plt.subplots(nrow,
                              ncol,
                              figsize=(4.9 * ncol, 5 * nrow),
                              sharex='col',
                              sharey='row')
    norm_th = matplotlib.cm.colors.Normalize(vmax=300, vmin=298)
    norm_w = matplotlib.cm.colors.Normalize(vmax=2.5, vmin=-2.5)
    # norm_vrad = matplotlib.cm.colors.Normalize(vmax=5, vmin=0)
    norm_vrad = matplotlib.cm.colors.Normalize(vmax=6, vmin=0)

    for i, t0 in enumerate(time_range):
        it = np.int(t0 / dt_fields)
        print('time: ', t0)

        fullpath_in = os.path.join(path_fields, str(t0) + '.nc')
        root_field = nc.Dataset(fullpath_in)
        grp = root_field.groups['fields']
        s = grp.variables['s'][:, :, k0]
        w = grp.variables['w'][:, :, k0]
        # v = grp.variables['v'][:,:,k0]
        # u = grp.variables['u'][:, :, k0]
        root_field.close()
        theta = thetas_c(s, 0.0)  # [ic - nx / 2:ic + nx / 2, :]
        # vorticity = vorticity_[it, :, :]
        vrad_2D = vrad_2D_[it, :, :]
        vtan_2D = vtan_2D_[it, :, :]

        axs = axes_[0, :]
        cf = axs[i].imshow(theta[ic:, jc:].T,
                           cmap=cm_bw_r,
                           norm=norm_th,
                           origin='lower')
        axins = plt.axes([axins_x[i], axins_y[0], axins_width, axins_width])
        axins.imshow(theta[imin:imax, imin:imax].T,
                     cmap=cm_bw_r,
                     norm=norm_th,
                     origin='lower')
        axins.set_aspect('equal')
        x_ticks = [np.int(n * dx[1] * 1e-3) for n in axins.get_xticks()]
        axins.set_xticklabels(x_ticks, fontsize=18)
        axins.set_yticklabels(x_ticks, fontsize=18)
        for label in axins.xaxis.get_ticklabels()[2::4]:
            label.set_visible(False)
        for label in axins.xaxis.get_ticklabels()[3::4]:
            label.set_visible(False)
        for label in axins.yaxis.get_ticklabels()[4::4]:
            label.set_visible(False)
        for label in axins.yaxis.get_ticklabels()[2::4]:
            label.set_visible(False)
        for label in axins.yaxis.get_ticklabels()[3::4]:
            label.set_visible(False)
        for label in axins.xaxis.get_ticklabels()[4::4]:
            label.set_visible(False)
        if t0 == time_range[-1]:
            cax = plt.axes([cbar_pos_x, 0.7, 0.012, 0.22])
            cbar = plt.colorbar(cf, cax=cax, ticks=np.arange(298, 300.1, 1))
            cbar.set_label(r'[K]', rotation=90)

        axs = axes_[1, :]
        cf = axs[i].imshow(w[ic:, jc:].T,
                           cmap=cm_bwr,
                           norm=norm_w,
                           origin='lower')
        # axins = plt.axes([axins_x[i], axins_y[1], axins_width, axins_width])
        # axins.imshow(w[imin:imax, imin:imax].T, cmap=cm_bwr, norm=norm_w, origin='lower')
        # axins.set_aspect('equal')
        # for label in axins.xaxis.get_ticklabels()[2::4]:
        #     label.set_visible(False)
        # for label in axins.xaxis.get_ticklabels()[3::4]:
        #     label.set_visible(False)
        # for label in axins.yaxis.get_ticklabels()[4::4]:
        #     label.set_visible(False)
        # for label in axins.yaxis.get_ticklabels()[2::4]:
        #     label.set_visible(False)
        # for label in axins.yaxis.get_ticklabels()[3::4]:
        #     label.set_visible(False)
        # for label in axins.xaxis.get_ticklabels()[4::4]:
        #     label.set_visible(False)
        # x_ticks = [np.int(n * dx[1] * 1e-3) for n in axins.get_xticks()]
        # axins.set_xticklabels(x_ticks)
        # axins.set_yticklabels(x_ticks)
        # for label in axins.xaxis.get_ticklabels()[0::2]:
        #     label.set_visible(False)
        # for label in axins.yaxis.get_ticklabels()[0::2]:
        #     label.set_visible(False)
        if t0 == time_range[-1]:
            cax = plt.axes([cbar_pos_x, 0.38, 0.012, 0.22])
            cbar = plt.colorbar(cf, cax=cax, ticks=np.arange(-3, 3 + 0.02, 1.))
            cbar.set_label(r'[m/s]')

        axs = axes_[2, :]
        # cf = axs[i].imshow(vrad_2D[ic:, jc:].T, cmap=cm_bw, norm=norm_vrad, origin='lower')
        cf = axs[i].imshow(vrad_2D[ic:, jc:].T,
                           cmap=cm_bw,
                           norm=colors.LogNorm(vmin=1e-2, vmax=2e1),
                           origin='lower')
        #phi = vtan_2D[ic:,jc:]
        #print('')
        #print('MINMAX: ', np.amin(phi), np.amax(phi))
        #print('')
        #lvls = np.arange(-2, 2.1, .5)
        #lvls = [-2, -1.5, -1, 1, 1.5, 2]
        ## lvls = [-1.5, 1.5]
        #ct = axs[i].contour(phi.T, 'r', levels=lvls)#levels=np.linspace(np.amin(phi), np.amax(phi),3))

        # axins = plt.axes([axins_x[i], axins_y[2], axins_width, axins_width])
        # axins.imshow(vrad_2D[imin:imax, imin:imax].T, cmap=cm_bw, norm=norm_vrad, origin='lower')
        # axins.set_aspect('equal')
        # for label in axins.xaxis.get_ticklabels()[2::4]:
        #     label.set_visible(False)
        # for label in axins.xaxis.get_ticklabels()[3::4]:
        #     label.set_visible(False)
        # for label in axins.yaxis.get_ticklabels()[4::4]:
        #     label.set_visible(False)
        # for label in axins.yaxis.get_ticklabels()[2::4]:
        #     label.set_visible(False)
        # for label in axins.yaxis.get_ticklabels()[3::4]:
        #     label.set_visible(False)
        # for label in axins.xaxis.get_ticklabels()[4::4]:
        #     label.set_visible(False)
        # x_ticks = [np.int(n * dx[1] * 1e-3) for n in axins.get_xticks()]
        # axins.set_xticklabels(x_ticks)
        # axins.set_yticklabels(x_ticks)
        # for label in axins.xaxis.get_ticklabels()[0::2]:
        #     label.set_visible(False)
        # for label in axins.yaxis.get_ticklabels()[0::2]:
        #     label.set_visible(False)
        if t0 == time_range[-1]:
            cax = plt.axes([cbar_pos_x, 0.06, 0.012, 0.22])
            #cbar = plt.colorbar(cf, cax=cax, ticks=np.arange(0, 5.1, 1), extend='max')
            cbar = plt.colorbar(cf, cax=cax, extend='min')
            cbar.set_label(r'[m/s]')
            #cbar_ct = plt.colorbar(ct, cax=cax)
            #cbar_ct.set_label(r'[m/s]')

        for ax in axes_[:, i].flat:
            ax.text(t_pos_x,
                    t_pos_y,
                    t_labels[i] + ' t=' + str(np.int(t0 / 60)) + 'min',
                    fontsize=24,
                    horizontalalignment='left',
                    bbox=textprops)

    for ax in axes_.flat:
        ax.set_xlim(0, 330)
        ax.set_ylim(0, 330)

        #ax.set_aspect('equal')
        x_ticks = [
            np.round((n - 50) * dx[0] * 1e-3, 2) for n in ax.get_xticks()
        ]
        ax.set_xticklabels(x_ticks)
        y_ticks = [np.round(n * dx[1] * 1e-3, 2) for n in ax.get_yticks()]
        ax.set_yticklabels(y_ticks)
        for label in ax.xaxis.get_ticklabels()[0::2]:
            label.set_visible(False)
        for label in ax.yaxis.get_ticklabels()[1::2]:
            label.set_visible(False)
    for ax in axes_[2, :].flat:
        ax.set_xlabel('x  [km]')
    for ax in axes_[:, 0].flat:
        ax.set_ylabel('y  [km]')

    textprops = dict(facecolor='white', alpha=0.9, linewidth=0.)
    title_pos_x = -50
    title_pos_y = 345
    title_font = 28
    txt = 'a) potential temperature'
    axes_[0, 0].text(title_pos_x,
                     title_pos_y,
                     txt,
                     fontsize=title_font,
                     horizontalalignment='left',
                     bbox=textprops)
    txt = 'b) vertical velocity'
    axes_[1, 0].text(title_pos_x,
                     title_pos_y,
                     txt,
                     fontsize=title_font,
                     horizontalalignment='left',
                     bbox=textprops)
    txt = 'c) radial velocity'
    axes_[2, 0].text(title_pos_x,
                     title_pos_y,
                     txt,
                     fontsize=title_font,
                     horizontalalignment='left',
                     bbox=textprops)

    #plt.subplots_adjust(bottom=0.05, right=.94, left=0.05, top=0.96, wspace=0.08, hspace=0.18)
    plt.subplots_adjust(bottom=0.05,
                        right=.92,
                        left=0.05,
                        top=0.96,
                        wspace=0.06,
                        hspace=0.18)
    print('saving: ', os.path.join(path_out_figs, fig_name))
    fig.savefig(os.path.join(path_out_figs, fig_name))
    plt.close(fig)

    return
Esempio n. 11
0
def figure_wholeCP_zoomasinsert(vrad_2D_, time_range, dt_fields, nx, dx, imin,
                                ic, jc, k0, path_fields, path_out_figs,
                                fig_name):

    # nlev = 2e2
    nlev = 2e1
    ncol = len(time_range)
    nrow = 3
    axins_x = [0.14, 0.3655, .594, .82]
    axins_y = [.815, .495, .175]
    axins_width = .13
    axins_xlim = [100, 180, 240, 280]
    textprops = dict(facecolor='white', alpha=0.9, linewidth=0.)
    t_pos_x = 30.
    t_pos_y = 650.
    t_labels = ['i)', 'ii)', 'iii)', 'iv)']
    imax = nx - imin

    fig, axes_ = plt.subplots(nrow,
                              ncol,
                              figsize=(4.9 * ncol, 5 * nrow),
                              sharex='col',
                              sharey='row')

    lvls_th = np.linspace(298, 300, nlev)
    lvls_w = np.linspace(-3, 3, nlev)
    lvls_vrad = np.linspace(-3, 3, nlev)
    norm_th = matplotlib.cm.colors.Normalize(vmax=300, vmin=298)
    norm_w = matplotlib.cm.colors.Normalize(vmax=2.5, vmin=-2.5)
    norm_vrad = matplotlib.cm.colors.Normalize(vmax=5, vmin=0)

    for i, t0 in enumerate(time_range):
        #if i < 2:
        #    continue
        it = np.int(t0 / dt_fields)
        print('time: ', t0)

        fullpath_in = os.path.join(path_fields, str(t0) + '.nc')
        root_field = nc.Dataset(fullpath_in)
        grp = root_field.groups['fields']
        s = grp.variables['s'][:, :, k0]
        w = grp.variables['w'][:, :, k0]
        # v = grp.variables['v'][:,:,k0]
        # u = grp.variables['u'][:, :, k0]
        root_field.close()
        theta = thetas_c(s, 0.0)  #[ic - nx / 2:ic + nx / 2, :]
        # vorticity = vorticity_[it, :, :]
        vrad_2D = vrad_2D_[it, :, :]

        axs = axes_[0, :]
        cf = axs[i].imshow(theta[imin:imax, imin:imax].T,
                           cmap=cm_bw_r,
                           norm=norm_th,
                           origin='lower')
        axins = plt.axes([axins_x[i], axins_y[0], axins_width, axins_width])
        axins.imshow(theta[ic + 48:, jc + 48:].T, cmap=cm_bw_r, norm=norm_th)
        axins.set_aspect('equal')
        axins.set_xlim(0, axins_xlim[i])
        axins.set_ylim(0, axins_xlim[i])
        #axins.set_xticklabels('')
        #axins.set_yticklabels('')
        x_ticks = [np.int(n * dx[1] * 1e-3) for n in axins.get_xticks()]
        axins.set_xticklabels(x_ticks)
        axins.set_yticklabels(x_ticks)
        for label in axins.xaxis.get_ticklabels()[1::2]:
            label.set_visible(False)
        for label in axins.yaxis.get_ticklabels()[1::2]:
            label.set_visible(False)
        if t0 == time_range[-1]:
            cax = plt.axes([0.95, 0.7, 0.012, 0.22])
            cbar = plt.colorbar(cf, cax=cax, ticks=np.arange(298, 300.1, 1))

        axs = axes_[1, :]
        cf = axs[i].imshow(w[imin:imax, imin:imax].T,
                           cmap=cm_bwr,
                           norm=norm_w,
                           origin='lower')
        axins = plt.axes([axins_x[i], axins_y[1], axins_width, axins_width])
        axins.imshow(w[ic + 48:, jc + 48:].T, cmap=cm_bwr, norm=norm_w)
        axins.set_aspect('equal')
        axins.set_xlim(0, axins_xlim[i])
        axins.set_ylim(0, axins_xlim[i])
        #axins.set_xticklabels('')
        #axins.set_yticklabels('')
        x_ticks = [np.int(n * dx[1] * 1e-3) for n in axins.get_xticks()]
        axins.set_xticklabels(x_ticks)
        axins.set_yticklabels(x_ticks)
        for label in axins.xaxis.get_ticklabels()[1::2]:
            label.set_visible(False)
        for label in axins.yaxis.get_ticklabels()[1::2]:
            label.set_visible(False)
        if t0 == time_range[-1]:
            cax = plt.axes([0.95, 0.38, 0.012, 0.22])
            cbar = plt.colorbar(cf, cax=cax, ticks=np.arange(-3, 3 + 0.02, 1.))

        axs = axes_[2, :]
        cf = axs[i].imshow(vrad_2D[imin:imax, imin:imax].T,
                           cmap=cm_bw,
                           norm=norm_vrad,
                           origin='lower')
        axins = plt.axes([axins_x[i], axins_y[2], axins_width, axins_width])
        axins.imshow(vrad_2D[ic + 48:, jc + 48:].T, cmap=cm_bw, norm=norm_vrad)
        axins.set_aspect('equal')
        axins.set_xlim(0, axins_xlim[i])
        axins.set_ylim(0, axins_xlim[i])
        #axins.set_xticklabels('')
        #axins.set_yticklabels('')
        x_ticks = [np.int(n * dx[1] * 1e-3) for n in axins.get_xticks()]
        axins.set_xticklabels(x_ticks)
        axins.set_yticklabels(x_ticks)
        for label in axins.xaxis.get_ticklabels()[1::2]:
            label.set_visible(False)
        for label in axins.yaxis.get_ticklabels()[1::2]:
            label.set_visible(False)
        if t0 == time_range[-1]:
            cax = plt.axes([0.95, 0.06, 0.012, 0.22])
            cbar = plt.colorbar(cf,
                                cax=cax,
                                ticks=np.arange(0, 5.1, 1),
                                extend='max')

        for ax in axes_[:, i].flat:
            # ax.text(t_pos_x, t_pos_y, 't='+str(np.int(t0/60))+'min', fontsize=18, horizontalalignment='left', bbox=textprops)
            ax.text(t_pos_x,
                    t_pos_y,
                    t_labels[i] + ' t=' + str(np.int(t0 / 60)) + 'min',
                    fontsize=24,
                    horizontalalignment='left',
                    bbox=textprops)

    #for ax in axes_[:,2].flat:
    #    ax.plot(ic,jc, 'ko', markersize=10)

    for ax in axes_.flat:
        # ax.set_xlim(imin, nx-imin)
        # ax.set_ylim(imin, ny-imin)
        ax.set_aspect('equal')
        x_ticks = [np.int(n * dx[0] * 1e-3) for n in ax.get_xticks()]
        # x_ticks = [np.int((n-imin)*dx[0]*1e-3) for n in ax.get_xticks()]
        ax.set_xticklabels(x_ticks)
        y_ticks = [np.int(n * dx[1] * 1e-3) for n in ax.get_yticks()]
        # y_ticks = [np.int((n-imin)*dx[0]*1e-3) for n in ax.get_yticks()]
        ax.set_yticklabels(y_ticks)
        #ax.set_xticks(np.arange(0, (nx-2*imin)*dx[0], step=1.e3))
        for label in ax.xaxis.get_ticklabels()[0::2]:
            label.set_visible(False)
        for label in ax.yaxis.get_ticklabels()[0::2]:
            label.set_visible(False)
    for ax in axes_[2, :].flat:
        ax.set_xlabel('x  [km]')
    for ax in axes_[:, 0].flat:
        ax.set_ylabel('y  [km]')

    textprops = dict(facecolor='white', alpha=0.9, linewidth=0.)
    title_pos_x = -120
    title_pos_y = imax
    title_font = 28
    txt = 'a) potential temperature'
    axes_[0, 0].text(title_pos_x,
                     title_pos_y,
                     txt,
                     fontsize=title_font,
                     horizontalalignment='left',
                     bbox=textprops)
    txt = 'b) vertical velocity'
    axes_[1, 0].text(title_pos_x,
                     title_pos_y,
                     txt,
                     fontsize=title_font,
                     horizontalalignment='left',
                     bbox=textprops)
    txt = 'c) radial velocity'
    axes_[2, 0].text(title_pos_x,
                     title_pos_y,
                     txt,
                     fontsize=title_font,
                     horizontalalignment='left',
                     bbox=textprops)

    # axes_[-1].legend(loc='upper center', bbox_to_anchor=(1.2, 1.),
    #                 fancybox=True, shadow=True, ncol=1, fontsize=10)
    plt.subplots_adjust(bottom=0.04,
                        right=.94,
                        left=0.05,
                        top=0.95,
                        wspace=0.08,
                        hspace=0.18)
    #fig.tight_layout()
    print('saving: ', os.path.join(path_out_figs, fig_name))
    fig.savefig(os.path.join(path_out_figs, fig_name))
    plt.close(fig)
    return
Esempio n. 12
0
def main():
    parser = argparse.ArgumentParser(prog='LES_CP')
    # parser.add_argument("--tmin")
    # parser.add_argument("--tmax")
    # parser.add_argument("--dx")
    # parser.add_argument("--shift")
    # parser.add_argument("--irmax")
    # parser.add_argument("--nsub")
    args = parser.parse_args()

    res = 50
    run = 'run3'
    dTh = 3
    rstar = 1000
    zstar = 1000
    case = 'dTh' + str(dTh) + '_z' + str(zstar) + '_r' + str(rstar)
    # case_name = args.casename
    case_name = 'ColdPoolDry_single_3D'

    path_root = '/nbi/ac/cond1/meyerbe/ColdPools/3D_sfc_fluxes_off/single_3D_noise/'
    path = os.path.join(path_root, run + '_dx' + str(res) + 'm', case)
    path_fields = os.path.join(path, 'fields')
    # path_out_figs = '/nbi/ac/cond1/meyerbe/paper_CP_single'
    path_out_figs = '/nbi/home/meyerbe/paper_CP'

    nml = simplejson.loads(open(os.path.join(path, case_name + '.in')).read())
    ic = nml['init']['ic']
    jc = nml['init']['jc']
    nx = nml['grid']['nx']
    ny = nml['grid']['ny']
    dx = np.ndarray(3, dtype=np.int)
    dx[0] = nml['grid']['dx']
    dx[1] = nml['grid']['dy']
    dx[2] = nml['grid']['dz']
    kmax = np.int(1.0e3 / dx[2])
    print('res: ' + str(dx))
    print('CP centre: ' + str(ic) + ', ' + str(jc))
    print('')

    root_vort = nc.Dataset(
        os.path.join(path, 'fields_vorticity/field_vort_xz.nc'))
    time_vort = root_vort.groups['fields'].variables['time'][:]
    vorticity_ = root_vort.groups['fields'].variables['vort_xz'][:, :, :kmax]
    root_vort.close()

    print('read in vorticity')
    root_vrad_2D = nc.Dataset(os.path.join(path, 'fields_v_rad/v_rad.nc'))
    # time_rad = root_vrad_2D.variables['time'][:]
    vrad_2D = root_vrad_2D.variables['v_rad'][:, :, jc, :kmax]
    root_vrad_2D.close()
    root_vrad = nc.Dataset(
        os.path.join(path, 'data_analysis/stats_radial_averaged.nc'))
    time_rad = root_vrad.groups['timeseries'].variables['time'][:]
    vrad = root_vrad.groups['stats'].variables['v_rad'][:, :, :kmax]
    root_vrad.close()

    imin_range = [150, 100, 100]
    for it, t0 in enumerate([900, 1200, 1500]):
        print('time: ', t0)
        # print('')
        imin = imin_range[it]
        imax = nx - imin
        fullpath_in = os.path.join(path_fields, str(t0) + '.nc')
        root_field = nc.Dataset(fullpath_in)
        grp = root_field.groups['fields']
        s = grp.variables['s'][:, jc, :kmax]
        w = grp.variables['w'][:, jc, :kmax]
        v = grp.variables['v'][:, jc, :kmax]
        root_field.close()
        theta = thetas_c(s, 0.0)[ic - nx / 2:ic + nx / 2, :]
        vorticity = vorticity_[np.int(t0 / 100), :, :]

        fig_name = 'CP_structure_dx' + str(res) + '_' + case + '_t' + str(
            t0) + '.png'
        # cm = plt.cm.get_cmap('rainbow')
        # cm_bwr = plt.cm.get_cmap('bwr')
        nlev = 2e2
        ncol = 2
        nrow = 4
        title_pos_x = 460
        title_pos_y = 26
        textprops = dict(facecolor='white', alpha=0.9, linewidth=0.)

        fig, axes = plt.subplots(nrow,
                                 ncol,
                                 sharex='col',
                                 figsize=(5 * ncol, 2 * nrow))
        for ax in axes[:, 1].flatten():
            ax.plot([jmin, jmax], [0, 0], '.5', linewidth=0.5)

        ax = axes[0, :]
        # min = 298
        min = np.round(np.amin(theta[:, :kmax]), 1)
        max = 300
        cf = ax[0].contourf(theta[:, :kmax].T,
                            levels=np.linspace(min, max, nlev),
                            cmap=cm_bw_r,
                            extend='max')
        cbar = plt.colorbar(cf,
                            ax=ax[0],
                            shrink=.75,
                            aspect=12,
                            ticks=np.arange(np.ceil(min), max + 0.5, 1.))
        ax[1].plot(theta[:, 0], 'k')
        ax[1].set_ylabel(r'$\theta$ [K]')
        ax[1].set_ylim(min, max)
        y_ticks = [np.int(ti) for ti in ax[1].get_yticks()]
        ax[1].set_yticklabels(y_ticks)
        for label in ax[1].yaxis.get_ticklabels()[1::2]:
            label.set_visible(False)
        ax[0].text(title_pos_x,
                   title_pos_y,
                   'a) potential temperature',
                   fontsize=15,
                   horizontalalignment='left',
                   bbox=textprops)

        ax = axes[1, :]
        min = -0.25
        max = -min
        cf = ax[0].contourf(v[:, :kmax].T,
                            levels=np.linspace(min, max, nlev),
                            cmap=cm_bwr,
                            extend='both')
        cbar = plt.colorbar(cf,
                            ax=ax[0],
                            shrink=0.75,
                            aspect=12,
                            ticks=np.arange(min, max + 0.1, 0.5))
        # cbar.set_label(cont_var_name, rotation=90)
        ax[1].plot(v[:, 1], 'k')
        ax[1].set_ylabel(r'$v_r$ [m/s]')
        ax[1].set_ylim(-7, max)
        y_ticks = [np.int(ti) for ti in ax[1].get_yticks()]
        ax[1].set_yticklabels(y_ticks)
        for label in ax[1].yaxis.get_ticklabels()[1::2]:
            label.set_visible(False)
        ax[0].text(title_pos_x,
                   title_pos_y,
                   'b) radial velocity',
                   fontsize=15,
                   horizontalalignment='left',
                   bbox=textprops)

        ax = axes[2, :]
        min = -2.
        max = -min
        cf = ax[0].contourf(w[:, :kmax].T,
                            levels=np.linspace(min, max, nlev),
                            cmap=cm_bwr,
                            extend='both')
        cbar = plt.colorbar(cf,
                            ax=ax[0],
                            shrink=0.75,
                            aspect=12,
                            ticks=np.arange(min, max + 0.5, 1.))
        ax[1].plot(w[:, 0], 'k')
        ax[1].set_ylabel(r'$w$ [m/s]')
        y_ticks = [np.int(ti) for ti in ax[1].get_yticks()]
        ax[1].set_yticklabels(y_ticks)
        for label in ax[1].yaxis.get_ticklabels()[1::2]:
            label.set_visible(False)
        ax[0].text(title_pos_x,
                   title_pos_y,
                   'c) vertical velocity',
                   fontsize=15,
                   horizontalalignment='left',
                   bbox=textprops)

        ax = axes[3, :]
        min = -0.1
        max = -min
        cf = ax[0].contourf(vorticity[:, :kmax].T,
                            levels=np.linspace(min, max, nlev),
                            cmap=cm_bwr,
                            extend='both')
        cbar = plt.colorbar(cf,
                            ax=ax[0],
                            shrink=0.75,
                            aspect=12,
                            ticks=np.arange(min, max + 0.02, 0.05))
        ax[1].plot(vorticity[:, 0], 'k')
        ax[1].set_ylabel(r'$\omega$ [m/s$^2$]')
        y_ticks = [ti for ti in ax[1].get_yticks()]
        ax[1].set_yticklabels(y_ticks)
        for label in ax[1].yaxis.get_ticklabels()[1::2]:
            label.set_visible(False)
        ax[0].text(title_pos_x,
                   title_pos_y,
                   'd) vorticity',
                   fontsize=15,
                   horizontalalignment='left',
                   bbox=textprops)

        speed = np.sqrt(v**2 + w**2)
        if speed[:, :kmax].max() > 0.:
            lw = 5 * speed[:, :kmax] / speed[:, :kmax].max()
        else:
            lw = 5 * speed[:, :kmax] / 1.
        # ax[1].streamplot(np.arange(nx), np.arange(kmax), v[:, :kmax].T, w[:, :kmax].T,
        #                  color='k', density=1.5, linewidth=lw[:, :].T)
        # ax[1].streamplot(np.arange(nx), np.arange(kmax), v[:, :kmax].T, w[:, :kmax].T, color='w')
        ax[1].streamplot(np.arange(nx),
                         np.arange(kmax),
                         w[:, :kmax].T,
                         v[:, :kmax].T,
                         density=1.5,
                         linewidth=lw[:, :].T)

        for ax in axes[:, 0].flat:
            ax.set_xlim(imin, imax)
            x_ticks = [ti * dx[0] * 1e-3 for ti in ax.get_xticks()]
            ax.set_xticklabels(x_ticks)
            y_ticks = [ti * dx[2] * 1e-3 for ti in ax.get_yticks()]
            ax.set_yticklabels(y_ticks)
            # for label in ax.yaxis.get_ticklabels()[1::2]:
            #     label.set_visible(dFalse)
            ax.set_ylabel('Height  [km]')
        for label in axes[-1, 0].yaxis.get_ticklabels()[1::2]:
            label.set_visible(False)
        for ax in axes[:, 1].flat:
            ax.set_xlim(imin, imax)
            x_ticks = [ti * dx[0] * 1e-3 for ti in ax.get_xticks()]
            ax.set_xticklabels(x_ticks)
            y_ticks = [ti for ti in ax.get_yticks()]
            ax.set_yticklabels(y_ticks)
            # for label in ax.yaxis.get_ticklabels()[1::2]:
            #     label.set_visible(False)
        for ax in axes[-1, :]:
            ax.set_xlabel('Radius [km]')

        # axes[-1].legend(loc='upper center', bbox_to_anchor=(1.2, 1.),
        #                 fancybox=True, shadow=True, ncol=1, fontsize=10)
        plt.subplots_adjust(bottom=0.06,
                            right=.95,
                            left=0.1,
                            top=0.95,
                            wspace=0.25,
                            hspace=0.45)
        # plt.suptitle('z=' + str(k0 * dx[2]) + 'm')
        fig.savefig(os.path.join(path_out_figs, fig_name))
        plt.close(fig)

    return