Esempio n. 1
0
def abs_vort_dt_at_pcent(run, rot_fac=1., lev=150.,lat_bound=45., res=0.01, interp=True):
    '''Calculate the (normalised) vorticity tendency at the precipitation centroid'''
    
    data = xr.open_dataset('/disca/share/rg419/Data_moist/climatologies/' + run + '.nc')
    
    # Interpolate in time if wanted
    if interp:
        times_new = np.arange(1., 72.2, 0.2)
        precip_new = time_interp(data.precipitation, times_new)
        u_new = time_interp(data.ucomp.sel(pfull=lev), times_new)
        v_new = time_interp(data.vcomp.sel(pfull=lev), times_new)
    else:
        precip_new = data.precipitation
        u_new = data.ucomp.sel(pfull=lev)
        v_new = data.vcomp.sel(pfull=lev)
        
    # Find precipitation centroid
    precip_new = make_sym(precip_new)
    data = xr.Dataset({'precipitation': precip_new}, coords=precip_new.coords)
    precip_centroid(data, lat_bound=lat_bound, res=res)
    
    # Calculate vorticity
    v_dx = gr.ddx(v_new)  # dvdx
    u_dy = gr.ddy(u_new)  # dudy
    omega = 7.2921150e-5 * rot_fac
    f = 2 * omega * np.sin(data.lat *np.pi/180)
    vor = (v_dx - u_dy + f)*86400.
    div = gr.ddx(u_new) + gr.ddy(v_new)
    stretching_mean = (-86400. * vor * div).mean('lon')
    vor = make_sym(vor, asym=True)
    stretching_mean = make_sym(stretching_mean, asym=True)
    
    # Take time derivative of absolute vorticity
    if interp:
        dvordt = gr.ddt(vor.mean('lon'))*86400.*5.
    else:
        dvordt = gr.ddt(vor.mean('lon'))*86400.
    # Also normalise this by the value of vorticity
    dvordtvor = dvordt/vor.mean('lon')
    #dvordtvor = stretching_mean/vor.mean('lon')
    
    # Interpolate vorticity in latitude to match precipitation centroid lats
    lats = [data.lat[i] for i in range(len(data.lat)) if data.lat[i] >= -lat_bound and data.lat[i] <= lat_bound]    
    lats_new = np.arange(-lat_bound, lat_bound+res, res)
    stretching_mean = lat_interp(stretching_mean.sel(lat=lats), lats_new)
    dvordt = lat_interp(dvordt.sel(lat=lats), lats_new)
    dvordtvor = lat_interp(dvordtvor.sel(lat=lats), lats_new)
    
    # Get and return dvordt and dvordtvor at the precipitation centroid, as well as the precipitation centroid itself
    st_pcent = [float(stretching_mean[i,:].sel(lat=data.p_cent.values[i]).values) for i in range(len(data.xofyear))]
    st_pcent = xr.DataArray(np.asarray(st_pcent), coords=[stretching_mean.xofyear.values], dims=['xofyear'])

    dvordt_pcent = [float(dvordt[i,:].sel(lat=data.p_cent.values[i]).values) for i in range(len(data.xofyear))]
    dvordt_pcent = xr.DataArray(np.asarray(dvordt_pcent), coords=[dvordt.xofyear.values], dims=['xofyear'])
    
    dvordtvor_pcent = [float(dvordtvor[i,:].sel(lat=data.p_cent.values[i]).values) for i in range(len(data.xofyear))]
    dvordtvor_pcent = xr.DataArray(np.asarray(dvordtvor_pcent), coords=[dvordtvor.xofyear.values], dims=['xofyear'])
    
    return dvordt_pcent, dvordtvor_pcent, data.p_cent, st_pcent
Esempio n. 2
0
def div_at_pcent(run,
                 rot_fac=1.,
                 lev=150.,
                 lat_bound=45.,
                 res=0.01,
                 interp=True):
    '''Calculate the (normalised) vorticity tendency at the precipitation centroid'''

    data = xr.open_dataset('/disca/share/rg419/Data_moist/climatologies/' +
                           run + '.nc')

    # Interpolate in time if wanted
    if interp:
        times_new = np.arange(1., 72.2, 0.2)
        precip_new = time_interp(data.precipitation, times_new)
        u_new = time_interp(data.ucomp.sel(pfull=lev), times_new)
        v_new = time_interp(data.vcomp.sel(pfull=lev), times_new)
    else:
        precip_new = data.precipitation
        u_new = data.ucomp.sel(pfull=lev)
        v_new = data.vcomp.sel(pfull=lev)

    # Find precipitation centroid
    precip_new = make_sym(precip_new)
    data = xr.Dataset({'precipitation': precip_new}, coords=precip_new.coords)
    precip_centroid(data, lat_bound=lat_bound, res=res)

    # Calculate divergence
    v_dx = gr.ddx(v_new)  # dvdx
    u_dy = gr.ddy(u_new)  # dudy
    div = (gr.ddx(u_new) + gr.ddy(v_new)).mean('lon') * 86400.
    omega = 7.2921150e-5 * rot_fac
    f = 2 * omega * np.sin(data.lat * np.pi / 180)
    vor = (-1. * gr.ddy(u_new) * 0. + f).mean('lon') * 86400.
    div = make_sym(div)
    vor = make_sym(vor, asym=True)
    div = div * vor
    div = vor
    # Interpolate divergence in latitude to match precipitation centroid lats
    lats = [
        data.lat[i] for i in range(len(data.lat))
        if data.lat[i] >= -lat_bound and data.lat[i] <= lat_bound
    ]
    lats_new = np.arange(-lat_bound, lat_bound + res, res)
    div = lat_interp(div.sel(lat=lats), lats_new)

    # Get and return dvordt and dvordtvor at the precipitation centroid, as well as the precipitation centroid itself
    div_pcent = [
        float(div[i, :].sel(lat=data.p_cent.values[i]).values)
        for i in range(len(data.xofyear))
    ]
    div_pcent = xr.DataArray(np.asarray(div_pcent),
                             coords=[div.xofyear.values],
                             dims=['xofyear'])

    return div_pcent, data.p_cent
Esempio n. 3
0
def abs_vort_dt_at_pcent(run, rot_fac=1., lev=150., lat_bound=45.):

    data = xr.open_dataset('/scratch/rg419/Data_moist/climatologies/' + run +
                           '.nc')
    data['precipitation'] = make_sym(data.precipitation)

    precip_centroid(data, lat_bound=lat_bound)

    v_dx = gr.ddx(data.vcomp)  # dvdx
    u_dy = gr.ddy(data.ucomp)  # dudy
    omega = 7.2921150e-5 * rot_fac
    f = 2 * omega * np.sin(data.lat * np.pi / 180)
    vor = (v_dx - u_dy + f).sel(pfull=lev) * 86400.

    vor = make_sym(vor, asym=True)

    # Take time derivative of absolute vorticity
    dvordt = gr.ddt(vor.mean('lon')) * 86400.

    # Select latitudes over which to evaluate precip centroid
    lats = [
        data.lat[i] for i in range(len(data.lat))
        if data.lat[i] >= -lat_bound and data.lat[i] <= lat_bound
    ]
    dvordt_lats = dvordt.sel(lat=lats).values
    #f_lats = f.sel(lat=lats).values

    # Interpolate vorticity tendency and f in latitude
    lats_new = np.arange(-lat_bound, lat_bound + 0.1, 0.1)

    fun = spint.interp1d(lats,
                         dvordt_lats,
                         axis=-1,
                         fill_value='extrapolate',
                         kind='quadratic')
    dvordt_new = fun(lats_new)
    dvordt = xr.DataArray(dvordt_new,
                          coords=[data.xofyear.values, lats_new],
                          dims=['xofyear', 'lat'])

    #fun = spint.interp1d(lats, f_lats, axis=-1, fill_value='extrapolate', kind='quadratic')
    #f_new = fun(lats_new)
    #f = xr.DataArray(f_new, coords=[lats_new], dims=['lat'])

    dvordt_pcent = [
        float(dvordt[i, :].sel(lat=data.p_cent.values[i]).values)
        for i in range(len(data.xofyear))
    ]
    #f_pcent = [float(f.sel(lat=data.p_cent.values[i]).values*86400.) for i in range(len(data.xofyear))]
    dvordt_pcent = xr.DataArray(np.asarray(dvordt_pcent),
                                coords=[data.xofyear.values],
                                dims=['xofyear'])

    return dvordt_pcent
Esempio n. 4
0
def p_cent_rate(data, days=False):
    """
    Inputs:
        data - xarray dataset climatology including precipitation as either precipitation or as convection_rain and condensation_rain
        days - instructs if data is in daily or pentad means
    Returns:
        dpcentdt - rate of movement of the precipitation centroid
        dpcentdt2 - rate of acceleration of the precipitation centroid
    """
    # Get total precip
    try:
        data['precipitation'] = data.condensation_rain + data.convection_rain
    except:
        data['precipitation'] = data.precipitation
    data['precipitation'] = make_sym(data.precipitation)

    # Locate precipitation centroid
    precip_centroid(data)

    # If units in are days rather than pentads (e.g. for shorter years) convert to pentads
    if days:
        dpcentdt = gr.ddt(data.p_cent, secperunit=86400.) * 86400.
    else:
        dpcentdt = gr.ddt(data.p_cent) * 86400.
    dpcentdt2 = gr.ddt(dpcentdt, secperunit=86400.) * 86400.

    return dpcentdt, dpcentdt2
Esempio n. 5
0
def rate_at_eq(runs, do_make_sym=True, days=None):
    dpdt_eq = []
    if days == None:
        days = [False] * len(runs)
    j = 0
    for run in runs:
        data = xr.open_dataset('/disca/share/rg419/Data_moist/climatologies/' +
                               run + '.nc')

        if do_make_sym:  # If symmetric data is wanted, average over both hemispheres (NB currently only set up for a climatology 2/05/18)
            data['precipitation'] = make_sym(data.precipitation)

        # Locate precipitation centroid
        precip_centroid(data)

        # Get rate of movement of precip centroid
        if days[j]:
            dpcentdt = gr.ddt(data.p_cent, secperunit=86400.) * 86400.
        else:
            dpcentdt = gr.ddt(data.p_cent) * 86400.
        #dpcentdt_max = dpcentdt_pmask.where(dpcentdt_pmask==dpcentdt_pmask.max('xofyear'),drop=True)   # Find the maximum rate
        p_cent = np.abs(data.p_cent.where(dpcentdt >= 0.))
        dpdt_eq_j = dpcentdt.where(p_cent == p_cent.min('xofyear'), drop=True)
        dpdt_eq.append(dpdt_eq_j.values[0])
        j = j + 1
    return np.asarray(dpdt_eq)
Esempio n. 6
0
def precip_psi_plot(run, ax, label='a)', p_cent=True):

    data = xr.open_dataset('/disca/share/rg419/Data_moist/climatologies/' +
                           run + '.nc')
    psi = mass_streamfunction(data, a=6376.0e3, dp_in=50.)
    psi /= 1.e9

    psi = make_sym(psi, asym=True)
    data['precipitation'] = make_sym(data.precipitation)

    f1 = precip_mse_plot(data,
                         ax,
                         plot_type='precip',
                         precip_contour=None,
                         p_cent=p_cent)

    psi.sel(pfull=500).plot.contour(ax=ax,
                                    x='xofyear',
                                    y='lat',
                                    levels=np.arange(-500., 0., 100.),
                                    add_labels=False,
                                    colors='0.7',
                                    linewidths=2,
                                    linestyles='--',
                                    alpha=0.7)
    psi.sel(pfull=500).plot.contour(ax=ax,
                                    x='xofyear',
                                    y='lat',
                                    levels=np.arange(0., 510., 100.),
                                    add_labels=False,
                                    colors='0.7',
                                    linewidths=2,
                                    alpha=0.7)
    psi.sel(pfull=500).plot.contour(ax=ax,
                                    x='xofyear',
                                    y='lat',
                                    levels=np.arange(-1000., 1010., 1000.),
                                    add_labels=False,
                                    colors='0.5',
                                    linewidths=2,
                                    alpha=0.7)

    ax.text(-10, 60, label)

    return f1
def vor_plot(run, ax, tf, linestyle='-', rot_fac=1., lev=150.):

    data = xr.open_dataset('/disca/share/rg419/Data_moist/climatologies/' +
                           run + '.nc')

    # Calculate vorticity
    v_dx = gr.ddx(data.vcomp)  # dvdx
    u_dy = gr.ddy(data.ucomp)  # dudy
    omega = 7.2921150e-5 * rot_fac
    f = 2 * omega * np.sin(data.lat * np.pi / 180)
    vor = (v_dx - u_dy + f).sel(pfull=lev) * 86400.

    div = (gr.ddx(data.ucomp) + gr.ddy(data.vcomp)).sel(pfull=lev)

    vor = (make_sym(vor, asym=True)).mean('lon')
    div = (make_sym(div)).mean('lon') * 8640.

    m = ((mc.omega * mc.a**2. * np.cos(data.lat * np.pi / 180.)**2. +
          data.ucomp.mean('lon') * mc.a * np.cos(data.lat * np.pi / 180.)).sel(
              pfull=lev)) / (mc.omega * mc.a**2.)

    #dvordt = gr.ddt(vor.mean('lon'))*86400.
    #stretching = (-86400. * vor * div).mean('lon')
    #adv = -86400. * (data.vcomp.sel(pfull=lev) * gr.ddy(vor, vector=False)).mean('lon')
    #dvordy = gr.ddy(vor, vector=False).mean('lon')*8640.

    #dvordy[tf[0]:tf[1],:].mean('xofyear').plot(ax=ax, color='r', linestyle=linestyle)
    #m[:,tf[0]:tf[1]].mean('xofyear').plot(ax=ax, color='r', linestyle=linestyle)
    vor[tf[0]:tf[1], :].mean('xofyear').plot(ax=ax,
                                             color='k',
                                             linestyle=linestyle)
    #stretching[tf[0]:tf[1],:].mean('xofyear').plot(ax=ax, color='b', linestyle=linestyle)
    #adv[tf[0]:tf[1],:].mean('xofyear').plot(ax=ax, color='r', linestyle=linestyle)
    #(stretching + adv)[tf[0]:tf[1],:].mean('xofyear').plot(ax=ax, color='r', linestyle=linestyle)

    ax.set_title('')
    ax.set_xlabel('')
    #ax.set_ylim(0.5,1.)
    ax.set_ylim(-10, 10)
    ax.grid(True, linestyle=':')
    ax.set_ylabel('Absolute vorticity, day$^{-1}$')
Esempio n. 8
0
def p_cent_rate_max(runs, days=None):
    # Get the maximum rate of change of the precipitation centroid latitude, and the latitude at which this occurs.
    
    max_rate = []
    max_rate_lat = []
    if days==None:
        days=[False]*len(runs)
        
    j=0
    for run in runs:
        # Open dataset
        data = xr.open_dataset('/scratch/rg419/Data_moist/climatologies/' + run + '.nc')
        
        # Get total precip
        try:
            data['precipitation'] = data.condensation_rain + data.convection_rain
        except:
            data['precipitation'] = data.precipitation
        
        data['precipitation'] = make_sym(data.precipitation)

        # Locate precipitation centroid
        precip_centroid(data)
            
        # Get rate of movement of precip centroid
        if days[j]:
            dpcentdt = gr.ddt(data.p_cent, secperunit = 86400.) * 86400.
        else:
            dpcentdt = gr.ddt(data.p_cent) * 86400.
                    
    
        dpcentdt_ppos = dpcentdt.where(data.p_cent>=0.)   # Find precip centroid rate where precip centroid is in the northern hemisphere
        dpcentdt_max = dpcentdt_ppos.where(dpcentdt_ppos==dpcentdt_ppos.max(),drop=True)   # Find the maximum of the above
        if len(dpcentdt_max) > 1:
            dpcentdt_max = dpcentdt_max[0]
        pcent_dtmax = data.p_cent.sel(xofyear=dpcentdt_max.xofyear)    # Find the location of the preciptiation when the rate is maximum
        
        print(dpcentdt_max.values, pcent_dtmax.values)     # Print both
        
        max_rate.append(dpcentdt_max)
        max_rate_lat.append(pcent_dtmax)
        
        j=j+1
    
    max_rate = np.asarray(max_rate)
    max_rate_lat = np.asarray(max_rate_lat)
    
    return max_rate, max_rate_lat
def plot_bs_fig_9_moist(run, pentads=[35, 40, 45, 50], rotfac=1.):

    plot_dir = '/scratch/rg419/plots/paper_2_figs/revisions/heatbudg_moist/'
    mkdir = sh.mkdir.bake('-p')
    mkdir(plot_dir)
    rcParams['figure.figsize'] = 5.5, 7.
    rcParams['font.size'] = 14

    data = xr.open_dataset('/disca/share/rg419/Data_moist/climatologies/' +
                           run + '.nc')
    data['precipitation'] = make_sym(data.precipitation)
    precip_centroid(data)  # Locate precipitation centroid
    dpcentdt = gr.ddt(data.p_cent) * 86400.
    p_cent_pos = np.abs(data.p_cent.where(dpcentdt >= 0.))

    eq_time = p_cent_pos.xofyear[p_cent_pos.argmin('xofyear').values]
    peak_rate_time = dpcentdt.xofyear[dpcentdt.argmax('xofyear').values]
    max_lat_time = data.p_cent.xofyear[data.p_cent.argmax('xofyear').values]

    edge_loc, psi_max, psi_max_loc = get_edge_psi(data,
                                                  lev=850.,
                                                  thresh=0.,
                                                  intdown=True)

    fig, (ax1, ax2, ax3, ax4) = plt.subplots(4, sharex=True)
    axes = [ax1, ax2, ax3, ax4]
    pentads = [
        eq_time.values, peak_rate_time.values,
        np.floor((peak_rate_time.values + max_lat_time.values) / 2.),
        max_lat_time.values
    ]

    for i in range(4):
        fig_9_moist(run, ax=axes[i], pentad=pentads[i])
        edge = edge_loc.sel(xofyear=pentads[i])
        axes[i].plot([edge, edge], [-250., 250.], 'k:')
        axes[i].text(20, 240., 'Pentad ' + str(int(pentads[i])))

    ax4.set_xlabel('Latitude')

    #ax1.text(-55, 315., 'a)')
    #ax2.text(-55, 315., 'b)')
    #ax3.text(-55, 315., 'c)')
    #ax4.text(-55, 315., 'd)')

    plt.subplots_adjust(left=0.15, right=0.95, top=0.97, bottom=0.1)
    plt.savefig(plot_dir + 'sb08_fig9_moist_' + run + '.pdf', format='pdf')
    plt.close()
def elliptical_equation(run, rotfac=1.):

    data = xr.open_dataset('/disca/share/rg419/Data_moist/climatologies/' + run + '.nc')
    data = data.mean('lon')
    
    data['precipitation'] = make_sym(data.precipitation)
    precip_centroid(data)       # Locate precipitation centroid
    dpcentdt = gr.ddt(data.p_cent) * 86400.
    p_cent_pos = np.abs(data.p_cent.where(dpcentdt>=0.))
       
    eq_time = p_cent_pos.xofyear[p_cent_pos.argmin('xofyear').values]
    peak_rate_time = dpcentdt.xofyear[dpcentdt.argmax('xofyear').values]
    max_lat_time = data.p_cent.xofyear[data.p_cent.argmax('xofyear').values]
    
    convTtotheta=(1000./data.pfull)**mc.kappa
    data['theta'] = data.temp*convTtotheta 
    #data['vcomp_theta'] = data.vcomp_temp*convTtotheta 
    #data['omega_theta'] = data.omega_temp*convTtotheta 
    #heating = data.dt_tg_condensation + data.dt_tg_convection + data.dt_tg_diffusion + data.tdt_rad
    #data['heating_theta'] = heating*convTtotheta
    
    sinphi = np.sin(data.lat * np.pi/180.)
    cosphi = np.cos(data.lat * np.pi/180.)
    
    #Calculate psi 
    #psi = mass_streamfunction(data, a=6376.0e3, dp_in=50.)
    
    dpsidydy = gr.ddy(data.omega, vector=False)
    rho = data.pfull*100./mc.rdgas/data.temp
    dthetadp = gr.ddp(data.theta)
    brunt_fac = -1./rho/data.theta * dthetadp
    psi_yy = (brunt_fac * dpsidydy)
    
    dpsidpdp = gr.ddp(-1.*data.vcomp)
    coriolis = 2.* rotfac * mc.omega * sinphi * data.vcomp
    dudy = gr.ddy(data.ucomp)
    cor_fac = -1.*dudy*coriolis + coriolis**2.
    psi_pp = (cor_fac * dpsidydy)
    
    dpsidpdy = gr.ddy(-1.*data.vcomp)
    dudp = gr.ddp(data.ucomp)
    psi_py = (2.*dudp*dpsidpdy*coriolis)
    
    duvdy = gr.ddy(data.ucomp_vcomp, uv=True)
    duwdp = gr.ddp(data.ucomp_omega)
    vdudy_mean = data.vcomp * dudy
    wdudp_mean = data.omega * dudp
    eddy_tend = -1.*duvdy -1.*duwdp + vdudy_mean + wdudp_mean
    M = data.dt_ug_diffusion + eddy_tend
    dMdp = (gr.ddp(M) * coriolis)
    
    dthetady = gr.ddy(data.theta, vector=False)
    #dvtdy = gr.ddy(data.vcomp_theta)
    #dwtdp = gr.ddp(data.omega_theta)
    vdtdy_mean = data.vcomp * dthetady
    wdtdp_mean = data.omega * dthetadp
    #eddy_tend_th = -1.*dvtdy -1.*dwtdp + vdtdy_mean + wdtdp_mean
    #J = data.heating_theta #+ eddy_tend_th
    #dJdy = (-1.* gr.ddy(J, vector=False)/rho/data.theta)
    
    plot_dir = '/scratch/rg419/plots/paper_2_figs/revisions/elliptical_eq/'
    mkdir = sh.mkdir.bake('-p')
    mkdir(plot_dir)
    rcParams['figure.figsize'] = 20., 12.
    
    levels = np.arange(-1.e-12,1.1e-12,0.1e-12)
    fig, ((ax1, ax2, ax3, ax4, ax5), (ax6, ax7, ax8, ax9, ax10), (ax11, ax12, ax13, ax14, ax15)) = plt.subplots(3, 5, sharey='row', sharex='col')
    axes = [ax1, ax2, ax3, ax4, ax5, ax6, ax7, ax8, ax9, ax10, ax11, ax12, ax13, ax14, ax15]
    
    i=0
    for time in [eq_time, peak_rate_time, max_lat_time]:
        f1 = psi_yy.sel(xofyear=time).plot.contourf(ax=axes[5*i], x='lat', y='pfull', yincrease=False, levels=levels, add_labels=False, extend='both', add_colorbar=False)
        psi_pp.sel(xofyear=time).plot.contourf(ax=axes[5*i+1], x='lat', y='pfull', yincrease=False, levels=levels, add_labels=False, extend='both', add_colorbar=False)
        psi_py.sel(xofyear=time).plot.contourf(ax=axes[5*i+2], x='lat', y='pfull', yincrease=False, levels=levels, add_labels=False, extend='both', add_colorbar=False)
        dMdp.sel(xofyear=time).plot.contourf(ax=axes[5*i+3], x='lat', y='pfull', yincrease=False, levels=levels, add_labels=False, extend='both', add_colorbar=False)
        #dJdy.sel(xofyear=time).plot.contourf(ax=axes[5*i+4], x='lat', y='pfull', yincrease=False, levels=levels, add_labels=False, extend='both', add_colorbar=False)
        i=i+1
    for ax in axes:
        ax.set_xlim(-30.,30.)
    
    ax1.set_title('N$^2d^2psi/dy^2$')
    ax2.set_title('$f(f-du/dy)d^2psi/dp^2$')
    ax3.set_title('Cross term')
    ax4.set_title('dM/dp')
    ax5.set_title('dJ/dy')
    plt.subplots_adjust(right=0.97, left=0.1, top=0.95, bottom=0., hspace=0.25, wspace=0.12)
    #Colorbar
    cb1=fig.colorbar(f1, ax=axes, use_gridspec=True, orientation = 'horizontal',fraction=0.15, pad=0.15, aspect=30, shrink=0.5)
    
    figname = 'elliptical_eq_' +run+ '.pdf'
    
    plt.savefig(plot_dir + figname, format='pdf')
    plt.close()    
Esempio n. 11
0
def abs_vort_dt_plot(run, rot_fac=1., lev=150.):

    data = xr.open_dataset('/disca/share/rg419/Data_moist/climatologies/' +
                           run + '.nc')

    psi = mass_streamfunction(data, a=6376.0e3, dp_in=50.)
    psi /= 1.e9

    data['precipitation'] = make_sym(data.precipitation)

    precip_centroid(data)

    v_dx = gr.ddx(data.vcomp)  # dvdx
    u_dy = gr.ddy(data.ucomp)  # dudy
    omega = 7.2921150e-5 * rot_fac
    f = 2 * omega * np.sin(data.lat * np.pi / 180)
    vor = (v_dx - u_dy + f).sel(pfull=lev) * 86400.

    # Take gradients of vorticity
    dvordx = gr.ddx(vor)
    dvordy = gr.ddy(vor, vector=False)

    # Horizontal material derivative
    horiz_md_mean = -86400. * (data.ucomp.sel(pfull=lev) * dvordx +
                               data.vcomp.sel(pfull=lev) * dvordy)

    # Calculate divergence and stretching term
    div = gr.ddx(data.ucomp.sel(pfull=lev)) + gr.ddy(data.vcomp.sel(pfull=lev))
    stretching_mean = -86400. * vor * div

    #vor = make_sym(vor, asym=True)
    #psi = make_sym(psi, asym=True)

    # Take time derivative of absolute vorticity
    dvordt = gr.ddt(vor.mean('lon')) * 86400.
    stretching_mean = stretching_mean.mean('lon')
    horiz_md_mean = horiz_md_mean.mean('lon')

    plot_dir = '/scratch/rg419/plots/paper_2_figs/abs_vort_dt/'
    mkdir = sh.mkdir.bake('-p')
    mkdir(plot_dir)

    rcParams['figure.figsize'] = 5, 12
    rcParams['font.size'] = 14

    fig, (ax1, ax2, ax3, ax4) = plt.subplots(4, 1)

    f1 = dvordt.plot.contourf(ax=ax1,
                              x='xofyear',
                              y='lat',
                              levels=np.arange(-0.06, 0.07, 0.01),
                              add_colorbar=False,
                              add_labels=False)
    psi.sel(pfull=500).plot.contour(ax=ax1,
                                    x='xofyear',
                                    y='lat',
                                    levels=np.arange(-500., 0., 100.),
                                    add_labels=False,
                                    colors='0.7',
                                    linewidths=2,
                                    linestyles='--')
    psi.sel(pfull=500).plot.contour(ax=ax1,
                                    x='xofyear',
                                    y='lat',
                                    levels=np.arange(0., 510., 100.),
                                    add_labels=False,
                                    colors='0.7',
                                    linewidths=2)
    psi.sel(pfull=500).plot.contour(ax=ax1,
                                    x='xofyear',
                                    y='lat',
                                    levels=np.arange(-1000., 1010., 1000.),
                                    add_labels=False,
                                    colors='0.5',
                                    linewidths=2)
    data.p_cent.plot.line(ax=ax1, color='k', linewidth=2)
    ax1.set_ylim([-60, 60])
    ax1.set_ylabel('Latitude')
    ax1.set_xticks([12, 24, 36, 48, 60, 72])
    ax1.set_yticks([-60, -30, 0, 30, 60])
    ax1.set_xlabel('Pentad')
    ax1.grid(True, linestyle=':')

    f1 = stretching_mean.plot.contourf(ax=ax2,
                                       x='xofyear',
                                       y='lat',
                                       levels=np.arange(-1.5, 1.6, 0.25),
                                       add_colorbar=False,
                                       add_labels=False)
    psi.sel(pfull=500).plot.contour(ax=ax2,
                                    x='xofyear',
                                    y='lat',
                                    levels=np.arange(-500., 0., 100.),
                                    add_labels=False,
                                    colors='0.7',
                                    linewidths=2,
                                    linestyles='--')
    psi.sel(pfull=500).plot.contour(ax=ax2,
                                    x='xofyear',
                                    y='lat',
                                    levels=np.arange(0., 510., 100.),
                                    add_labels=False,
                                    colors='0.7',
                                    linewidths=2)
    psi.sel(pfull=500).plot.contour(ax=ax2,
                                    x='xofyear',
                                    y='lat',
                                    levels=np.arange(-1000., 1010., 1000.),
                                    add_labels=False,
                                    colors='0.5',
                                    linewidths=2)
    data.p_cent.plot.line(ax=ax2, color='k', linewidth=2)
    ax2.set_ylim([-60, 60])
    ax2.set_ylabel('Latitude')
    ax2.set_xticks([12, 24, 36, 48, 60, 72])
    ax2.set_yticks([-60, -30, 0, 30, 60])
    ax2.set_xlabel('Pentad')
    ax2.grid(True, linestyle=':')

    f1 = horiz_md_mean.plot.contourf(ax=ax3,
                                     x='xofyear',
                                     y='lat',
                                     levels=np.arange(-1.5, 1.6, 0.25),
                                     add_colorbar=False,
                                     add_labels=False)
    psi.sel(pfull=500).plot.contour(ax=ax3,
                                    x='xofyear',
                                    y='lat',
                                    levels=np.arange(-500., 0., 100.),
                                    add_labels=False,
                                    colors='0.7',
                                    linewidths=2,
                                    linestyles='--')
    psi.sel(pfull=500).plot.contour(ax=ax3,
                                    x='xofyear',
                                    y='lat',
                                    levels=np.arange(0., 510., 100.),
                                    add_labels=False,
                                    colors='0.7',
                                    linewidths=2)
    psi.sel(pfull=500).plot.contour(ax=ax3,
                                    x='xofyear',
                                    y='lat',
                                    levels=np.arange(-1000., 1010., 1000.),
                                    add_labels=False,
                                    colors='0.5',
                                    linewidths=2)
    data.p_cent.plot.line(ax=ax3, color='k', linewidth=2)
    ax3.set_ylim([-60, 60])
    ax3.set_ylabel('Latitude')
    ax3.set_xticks([12, 24, 36, 48, 60, 72])
    ax3.set_yticks([-60, -30, 0, 30, 60])
    ax3.set_xlabel('Pentad')
    ax3.grid(True, linestyle=':')

    f1 = (stretching_mean + horiz_md_mean).plot.contourf(ax=ax4,
                                                         x='xofyear',
                                                         y='lat',
                                                         levels=np.arange(
                                                             -1.5, 1.6, 0.25),
                                                         add_colorbar=False,
                                                         add_labels=False)
    psi.sel(pfull=500).plot.contour(ax=ax4,
                                    x='xofyear',
                                    y='lat',
                                    levels=np.arange(-500., 0., 100.),
                                    add_labels=False,
                                    colors='0.7',
                                    linewidths=2,
                                    linestyles='--')
    psi.sel(pfull=500).plot.contour(ax=ax4,
                                    x='xofyear',
                                    y='lat',
                                    levels=np.arange(0., 510., 100.),
                                    add_labels=False,
                                    colors='0.7',
                                    linewidths=2)
    psi.sel(pfull=500).plot.contour(ax=ax4,
                                    x='xofyear',
                                    y='lat',
                                    levels=np.arange(-1000., 1010., 1000.),
                                    add_labels=False,
                                    colors='0.5',
                                    linewidths=2)
    data.p_cent.plot.line(ax=ax4, color='k', linewidth=2)
    ax4.set_ylim([-60, 60])
    ax4.set_ylabel('Latitude')
    ax4.set_xticks([12, 24, 36, 48, 60, 72])
    ax4.set_yticks([-60, -30, 0, 30, 60])
    ax4.set_xlabel('Pentad')
    ax4.grid(True, linestyle=':')

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

    cb1 = fig.colorbar(f1,
                       ax=ax1,
                       use_gridspec=True,
                       orientation='horizontal',
                       fraction=0.15,
                       pad=0.2,
                       aspect=40)
    cb1.set_label('Absolute vorticity tendency, day$^{-2}$')

    plt.savefig(plot_dir + 'vort_terms_' + run + '.pdf', format='pdf')
    plt.close()
Esempio n. 12
0
def local_pcent_plots(run,
                      regions=[[350, 10], [80, 100], [170, 190], [260, 280]],
                      do_make_sym=True):

    data = xr.open_dataset('/disca/share/rg419/Data_moist/climatologies/' +
                           run + '.nc')

    if do_make_sym:
        data['precipitation'] = make_sym(data.precipitation)

    data = precip_centroid_ll(data, lat_bound=30.)

    def get_lons(lonin, data):
        if lonin[1] > lonin[0]:
            lons = [
                data.lon[i] for i in range(len(data.lon))
                if data.lon[i] >= lonin[0] and data.lon[i] < lonin[1]
            ]
        else:
            lons = [
                data.lon[i] for i in range(len(data.lon))
                if data.lon[i] >= lonin[0] or data.lon[i] < lonin[1]
            ]
        return lons

    lons_1 = get_lons(regions[0], data)
    lons_2 = get_lons(regions[1], data)
    lons_3 = get_lons(regions[2], data)
    lons_4 = get_lons(regions[3], data)

    dpcentdt_1 = gr.ddt(data.p_cent.sel(lon=lons_1).mean('lon')) * 86400.
    dpcentdt_2 = gr.ddt(data.p_cent.sel(lon=lons_2).mean('lon')) * 86400.
    dpcentdt_3 = gr.ddt(data.p_cent.sel(lon=lons_3).mean('lon')) * 86400.
    dpcentdt_4 = gr.ddt(data.p_cent.sel(lon=lons_4).mean('lon')) * 86400.

    # Set figure parameters
    rcParams['figure.figsize'] = 10, 7
    rcParams['font.size'] = 14
    # Start figure with 4 subplots
    fig, ((ax1, ax2), (ax3, ax4)) = plt.subplots(2, 2)

    ax1.plot(data.p_cent.sel(lon=lons_1).mean('lon'),
             dpcentdt_1,
             'kx',
             mew=2,
             ms=10,
             alpha=0.5)
    ax1.plot(data.p_cent.sel(lon=lons_1).mean('lon'),
             dpcentdt_1,
             alpha=0.3,
             color='k',
             linewidth=2)
    ax1.set_title('West coast')

    ax2.plot(data.p_cent.sel(lon=lons_2).mean('lon'),
             dpcentdt_2,
             'kx',
             mew=2,
             ms=10,
             alpha=0.5)
    ax2.plot(data.p_cent.sel(lon=lons_2).mean('lon'),
             dpcentdt_2,
             alpha=0.3,
             color='k',
             linewidth=2)
    ax2.set_title('Land')

    ax3.plot(data.p_cent.sel(lon=lons_3).mean('lon'),
             dpcentdt_3,
             'kx',
             mew=2,
             ms=10,
             alpha=0.5)
    ax3.plot(data.p_cent.sel(lon=lons_3).mean('lon'),
             dpcentdt_3,
             alpha=0.3,
             color='k',
             linewidth=2)
    ax3.set_title('East coast')

    ax4.plot(data.p_cent.sel(lon=lons_4).mean('lon'),
             dpcentdt_4,
             'kx',
             mew=2,
             ms=10,
             alpha=0.5)
    ax4.plot(data.p_cent.sel(lon=lons_4).mean('lon'),
             dpcentdt_4,
             alpha=0.3,
             color='k',
             linewidth=2)
    ax4.set_title('Ocean')

    ax3.set_xlabel('ITCZ latitude')
    ax4.set_xlabel('ITCZ latitude')
    ax1.set_ylabel('ITCZ migration rate')
    ax3.set_ylabel('ITCZ migration rate')

    for ax in [ax1, ax2, ax3, ax4]:
        ax.grid(True, linestyle=':')
        ax.set_xlim(-25, 25)
        ax.set_ylim(-1.0, 1.0)

    plt.subplots_adjust(left=0.1,
                        right=0.97,
                        top=0.95,
                        bottom=0.1,
                        hspace=0.3,
                        wspace=0.3)

    # Save as a pdf
    plt.savefig(plot_dir + 'bowties_' + run + '.pdf', format='pdf')
    plt.close()

    # Start figure with 4 subplots
    fig, ((ax1, ax2), (ax3, ax4)) = plt.subplots(2, 2)

    precip_mse_plot(data, ax1, lonin=regions[0], lat_bound=30.)
    precip_mse_plot(data, ax2, lonin=regions[1], lat_bound=30.)
    precip_mse_plot(data, ax3, lonin=regions[2], lat_bound=30.)
    precip_mse_plot(data, ax4, lonin=regions[3], lat_bound=30.)

    ax1.set_title('West coast')
    ax2.set_title('Land')
    ax3.set_title('East coast')
    ax4.set_title('Ocean')

    ax3.set_xlabel('Pentad')
    ax4.set_xlabel('Pentad')
    ax1.set_ylabel('Latitude')
    ax3.set_ylabel('Latitude')

    for ax in [ax1, ax2, ax3, ax4]:
        ax.grid(True, linestyle=':')

    plt.subplots_adjust(left=0.1,
                        right=0.97,
                        top=0.95,
                        bottom=0.1,
                        hspace=0.3,
                        wspace=0.3)

    # Save as a pdf
    plt.savefig(plot_dir + 'precip_' + run + '.pdf', format='pdf')
    plt.close()

    data.close()
Esempio n. 13
0
def abs_vort_dt_plot(run, rot_fac=1., lev=150.):

    data = xr.open_dataset('/scratch/rg419/Data_moist/climatologies/' + run +
                           '.nc')

    psi = mass_streamfunction(data, a=6376.0e3, dp_in=50.)
    psi /= 1.e9

    data['precipitation'] = make_sym(data.precipitation)

    precip_centroid(data)

    v_dx = gr.ddx(data.vcomp)  # dvdx
    u_dy = gr.ddy(data.ucomp)  # dudy
    omega = 7.2921150e-5 * rot_fac
    f = 2 * omega * np.sin(data.lat * np.pi / 180)
    vor = (v_dx - u_dy + f).sel(pfull=lev) * 86400.

    vor = make_sym(vor, asym=True)
    psi = make_sym(psi, asym=True)

    # Take time derivative of absolute vorticity
    dvordt = gr.ddt(vor.mean('lon')) * 86400.

    plot_dir = '/scratch/rg419/plots/paper_2_figs/abs_vort_dt/'
    mkdir = sh.mkdir.bake('-p')
    mkdir(plot_dir)

    rcParams['figure.figsize'] = 5.5, 4.3
    rcParams['font.size'] = 16

    fig = plt.figure()
    ax1 = fig.add_subplot(111)

    f1 = dvordt.plot.contourf(ax=ax1,
                              x='xofyear',
                              y='lat',
                              levels=np.arange(-0.06, 0.07, 0.01),
                              add_colorbar=False,
                              add_labels=False)
    psi.sel(pfull=500).plot.contour(ax=ax1,
                                    x='xofyear',
                                    y='lat',
                                    levels=np.arange(-500., 0., 100.),
                                    add_labels=False,
                                    colors='0.7',
                                    linewidths=2,
                                    linestyles='--')
    psi.sel(pfull=500).plot.contour(ax=ax1,
                                    x='xofyear',
                                    y='lat',
                                    levels=np.arange(0., 510., 100.),
                                    add_labels=False,
                                    colors='0.7',
                                    linewidths=2)
    psi.sel(pfull=500).plot.contour(ax=ax1,
                                    x='xofyear',
                                    y='lat',
                                    levels=np.arange(-1000., 1010., 1000.),
                                    add_labels=False,
                                    colors='0.5',
                                    linewidths=2)
    data.p_cent.plot.line(color='k', linewidth=2)
    ax1.set_ylim([-60, 60])
    ax1.set_ylabel('Latitude')
    ax1.set_xticks([12, 24, 36, 48, 60, 72])
    ax1.set_yticks([-60, -30, 0, 30, 60])
    ax1.set_xlabel('Pentad')
    ax1.grid(True, linestyle=':')

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

    cb1 = fig.colorbar(f1,
                       ax=ax1,
                       use_gridspec=True,
                       orientation='horizontal',
                       fraction=0.15,
                       pad=0.2,
                       aspect=40)
    cb1.set_label('Absolute vorticity tendency, day$^{-2}$')

    plt.savefig(plot_dir + 'abs_vort_dt_' + run + '.pdf', format='pdf')
    plt.close()
def ang_mom_grad_plot(run, rot_fac=1., lev=150.):
    '''Plot dvordt or 1/vor * dvordt'''

    #Load data
    data = xr.open_dataset('/disca/share/rg419/Data_moist/climatologies/' +
                           run + '.nc')

    #Calculate psi to overplot
    psi = mass_streamfunction(data, a=6376.0e3, dp_in=50.)
    psi /= 1.e9
    psi = make_sym(psi, asym=True)

    # Make precip symmetric and find the precip centroid
    data['precipitation'] = make_sym(data.precipitation)
    precip_centroid(data)
    data['ucomp'] = make_sym(data.ucomp)
    data['vcomp'] = make_sym(data.vcomp, asym=True)
    data['omega'] = make_sym(data.omega)

    # Calculate vorticity
    v_dx = gr.ddx(data.vcomp)  # dvdx
    u_dy = gr.ddy(data.ucomp)  # dudy
    u_dp = gr.ddp(data.ucomp)  # dudp

    omega = 7.2921150e-5 * rot_fac
    f = 2 * omega * np.sin(data.lat * np.pi / 180)
    vor = (v_dx - u_dy + f).sel(pfull=lev).mean('lon') * 86400.

    vertical_term = (-1. * data.omega / data.vcomp *
                     u_dp).sel(pfull=lev).mean('lon') * 86400.

    ang_mom_grad = vor + vertical_term

    # Plot!
    plot_dir = '/scratch/rg419/plots/paper_2_figs/ang_mom_grad/'
    mkdir = sh.mkdir.bake('-p')
    mkdir(plot_dir)

    rcParams['figure.figsize'] = 5.5, 4.3
    rcParams['font.size'] = 14

    fig = plt.figure()
    ax1 = fig.add_subplot(111)

    f1 = ang_mom_grad.plot.contourf(ax=ax1,
                                    x='xofyear',
                                    y='lat',
                                    levels=np.arange(-6., 6.1, 1.),
                                    add_colorbar=False,
                                    add_labels=False,
                                    extend='both')
    psi.sel(pfull=lev).plot.contour(ax=ax1,
                                    x='xofyear',
                                    y='lat',
                                    levels=np.arange(-500., 0., 100.),
                                    add_labels=False,
                                    colors='0.7',
                                    linewidths=2,
                                    linestyles='--')
    psi.sel(pfull=lev).plot.contour(ax=ax1,
                                    x='xofyear',
                                    y='lat',
                                    levels=np.arange(0., 510., 100.),
                                    add_labels=False,
                                    colors='0.7',
                                    linewidths=2)
    psi.sel(pfull=lev).plot.contour(ax=ax1,
                                    x='xofyear',
                                    y='lat',
                                    levels=np.arange(-1000., 1010., 1000.),
                                    add_labels=False,
                                    colors='0.5',
                                    linewidths=2)
    data.p_cent.plot.line(ax=ax1, color='k', linewidth=2)
    ax1.set_ylim([-60, 60])
    ax1.set_ylabel('Latitude')
    ax1.set_xticks([12, 24, 36, 48, 60, 72])
    ax1.set_yticks([-60, -30, 0, 30, 60])
    ax1.set_xlabel('Pentad')
    ax1.grid(True, linestyle=':')
    plt.subplots_adjust(left=0.17,
                        right=0.9,
                        top=0.97,
                        bottom=0.07,
                        hspace=0.3)

    cb1 = fig.colorbar(f1,
                       ax=ax1,
                       use_gridspec=True,
                       orientation='horizontal',
                       fraction=0.15,
                       pad=0.2,
                       aspect=40)
    cb1.set_label('Angular momentum gradient')

    plt.savefig(plot_dir + 'ang_mom_grad_' + run + '.pdf', format='pdf')
    plt.close()
Esempio n. 15
0
def div_plot(run, ax, rot_fac=1., lev=150.):
    '''Plot dvordt or 1/vor * dvordt'''

    #Load data
    data = xr.open_dataset('/disca/share/rg419/Data_moist/climatologies/' +
                           run + '.nc')

    #Calculate psi to overplot
    psi = mass_streamfunction(data, a=6376.0e3, dp_in=50.)
    psi /= 1.e9
    psi = make_sym(psi, asym=True)

    # Make precip symmetric and find the precip centroid
    data['precipitation'] = make_sym(data.precipitation)
    precip_centroid(data)

    # Calculate divergence
    u_dx = gr.ddx(data.ucomp)  # dudx
    v_dy = gr.ddy(data.vcomp)  # dvdy
    div = (u_dx + v_dy).sel(pfull=lev) * 86400.
    div = make_sym(div)
    div = div.mean('lon')

    f1 = div.plot.contourf(ax=ax,
                           x='xofyear',
                           y='lat',
                           levels=np.arange(-1.2, 1.3, 0.2),
                           add_colorbar=False,
                           add_labels=False)

    psi.sel(pfull=500).plot.contour(ax=ax,
                                    x='xofyear',
                                    y='lat',
                                    levels=np.arange(-500., 0., 100.),
                                    add_labels=False,
                                    colors='0.7',
                                    linewidths=2,
                                    linestyles='--')
    psi.sel(pfull=500).plot.contour(ax=ax,
                                    x='xofyear',
                                    y='lat',
                                    levels=np.arange(0., 510., 100.),
                                    add_labels=False,
                                    colors='0.7',
                                    linewidths=2)
    psi.sel(pfull=500).plot.contour(ax=ax,
                                    x='xofyear',
                                    y='lat',
                                    levels=np.arange(-1000., 1010., 1000.),
                                    add_labels=False,
                                    colors='0.5',
                                    linewidths=2)
    data.p_cent.plot.line(ax=ax, color='k', linewidth=2)
    ax.set_ylim([-60, 60])
    ax.set_ylabel('Latitude')
    ax.set_xticks([12, 24, 36, 48, 60, 72])
    ax.set_yticks([-60, -30, 0, 30, 60])
    ax.set_xlabel('Pentad')
    ax.grid(True, linestyle=':')

    box = ax.get_position()
    axColor = plt.axes(
        [box.x0 + box.width * 0.92, box.y0 + box.y0 * 0.12, 0.015, box.height])
    cb1 = fig.colorbar(f1, cax=axColor, orientation='vertical')
Esempio n. 16
0
def vdtdy_plot(run, ax, lev=850.):

    data = xr.open_dataset('/disca/share/rg419/Data_moist/climatologies/' +
                           run + '.nc')

    psi = mass_streamfunction(data, a=6376.0e3, dp_in=50.)
    psi /= 1.e9

    try:
        data['precipitation'] = make_sym(data.precipitation)
    except:
        data['precipitation'] = data.convection_rain + data.condensation_rain
        data['precipitation'] = make_sym(data.precipitation)

    precip_centroid(data)

    convTtotheta = (1000. / data.pfull)**(2. / 7.)
    theta = data.temp * convTtotheta

    rho = lev * 100. / Rd / data.temp.sel(
        pfull=lev) / (1 + (Rv - Rd) / Rd * data.sphum.sel(pfull=lev))

    expansion_term = (1. / rho / cp *
                      data.omega.sel(pfull=lev)).mean('lon') * 86400.
    #expansion_term = (1./rho/cp ).mean('lon') * 86400.

    v = data.vcomp.sel(pfull=lev)  # v
    T_dy = -86400. * gr.ddy(data.temp.sel(pfull=lev), vector=False)  # dTdy
    vdTdy = v.mean('lon') * T_dy.mean('lon')  # [v][dTdy]

    w = data.omega.sel(pfull=lev)  # w
    T_dp = -86400. * (gr.ddp(data.temp)).sel(pfull=lev)  # dTdp
    wdTdp = w.mean('lon') * T_dp.mean('lon')  # [w][dTdp]

    dTdt = gr.ddt(data.temp).sel(pfull=lev).mean('lon') * 86400.
    #dvtdy = -1.*(gr.ddy(data.vcomp * data.temp)).mean('lon').sel(pfull=lev)*86400.
    #dwtdp = -1.*(gr.ddp(data.omega * data.temp)).mean('lon').sel(pfull=lev)*86400.

    #dvtdy_colav = -1.*gr.ddy((data.vcomp * theta).mean('lon').sel(pfull=np.arange(50.,501.,50.)).mean('pfull')*5000./9.8)*1004.64

    #dvHdy_colav = -1.*gr.ddy((data.vcomp * (data.temp*1004.64 + data.sphum*2.500e6)).mean('lon').mean('pfull')*5000./9.8)

    #f1 = (dvtdy_colav).plot.contourf(ax=ax, x='xofyear', y='lat', add_labels=False, levels=np.arange(-30.,33.,3.), extend='both', add_colorbar=False)
    #f1 = (vdTdy).plot.contourf(ax=ax, x='xofyear', y='lat', add_labels=False, levels=np.arange(-5.,5.5,0.5), extend='both', add_colorbar=False)
    f1 = (vdTdy + wdTdp).plot.contourf(ax=ax,
                                       x='xofyear',
                                       y='lat',
                                       add_labels=False,
                                       levels=np.arange(-3., 3.1, 0.5),
                                       extend='both',
                                       add_colorbar=False)
    #f1 = (dTdt).plot.contourf(ax=ax, x='xofyear', y='lat', add_labels=False, levels=np.arange(-0.2,0.21,0.02), extend='both', add_colorbar=False)
    #f1 = (vdTdy + wdTdp + expansion_term).plot.contourf(ax=ax, x='xofyear', y='lat', add_labels=False,  extend='both', add_colorbar=False)
    #f1 = (-1.*expansion_term-T_dp.mean('lon')).plot.contourf(ax=ax, x='xofyear', y='lat', add_labels=False,  extend='both', add_colorbar=False)
    psi.sel(pfull=500).plot.contour(ax=ax,
                                    x='xofyear',
                                    y='lat',
                                    levels=np.arange(-500., 0., 100.),
                                    add_labels=False,
                                    colors='0.7',
                                    linewidths=2,
                                    linestyles='--')
    psi.sel(pfull=500).plot.contour(ax=ax,
                                    x='xofyear',
                                    y='lat',
                                    levels=np.arange(0., 510., 100.),
                                    add_labels=False,
                                    colors='0.7',
                                    linewidths=2)
    psi.sel(pfull=500).plot.contour(ax=ax,
                                    x='xofyear',
                                    y='lat',
                                    levels=np.arange(-1000., 1010., 1000.),
                                    add_labels=False,
                                    colors='0.5',
                                    linewidths=2)
    data.p_cent.plot.line(ax=ax, color='k', linewidth=2)
    ax.set_xlabel('')
    ax.set_ylim([-60, 60])
    ax.set_ylabel('Latitude')
    ax.set_xticks([12, 24, 36, 48, 60, 72])
    ax.set_yticks([-60, -30, 0, 30, 60])
    ax.grid(True, linestyle=':')

    return f1
Esempio n. 17
0
def abs_vort_dt_plot(run, ax, rot_fac=1., lev=150., dvordt_flag=False):
    '''Plot dvordt or 1/vor * dvordt'''
    
    #Load data
    data = xr.open_dataset('/disca/share/rg419/Data_moist/climatologies/' + run + '.nc')
    
    #Calculate psi to overplot
    psi = mass_streamfunction(data, a=6376.0e3, dp_in=50.)
    psi /= 1.e9
    psi = make_sym(psi, asym=True)
    
    # Make precip symmetric and find the precip centroid
    data['precipitation'] = make_sym(data.precipitation)
    precip_centroid(data)
    
    # Calculate vorticity
    v_dx = gr.ddx(data.vcomp)  # dvdx
    u_dy = gr.ddy(data.ucomp)  # dudy
    omega = 7.2921150e-5 * rot_fac
    f = 2 * omega * np.sin(data.lat *np.pi/180)
    vor = (v_dx - u_dy + f).sel(pfull=lev)*86400.

    vor = make_sym(vor, asym=True)
    
    # Take time derivative of absolute vorticity
    dvordt = gr.ddt(vor.mean('lon'))*86400.
    # Also normalise this by the value of vorticity
    dvordtvor = dvordt/vor.mean('lon')
    
    # Plot!
    plot_dir = '/scratch/rg419/plots/paper_2_figs/abs_vort_dt/'
    mkdir = sh.mkdir.bake('-p')
    mkdir(plot_dir)
    
    rcParams['figure.figsize'] = 5.5, 4.3
    rcParams['font.size'] = 14

    #fig = plt.figure()
    #ax1 = fig.add_subplot(111)    
    
    if dvordt_flag:
        f1 = dvordt.plot.contourf(ax=ax, x='xofyear', y='lat', levels=np.arange(-0.06,0.07,0.01), add_colorbar=False, add_labels=False)
    else:
        f1 = dvordtvor.plot.contourf(ax=ax, x='xofyear', y='lat', levels=np.arange(-0.05,0.055,0.005),  add_colorbar=False, add_labels=False)
    #psi.sel(pfull=500).plot.contour(ax=ax, x='xofyear', y='lat', levels=np.arange(-500.,0.,100.), add_labels=False, colors='0.7', linewidths=2, linestyles='--')
    #psi.sel(pfull=500).plot.contour(ax=ax, x='xofyear', y='lat', levels=np.arange(0.,510.,100.), add_labels=False, colors='0.7', linewidths=2)
    #psi.sel(pfull=500).plot.contour(ax=ax, x='xofyear', y='lat', levels=np.arange(-1000.,1010.,1000.), add_labels=False, colors='0.5', linewidths=2)
    data.p_cent.plot.line(ax=ax, color='k', linewidth=2)
    ax.set_ylim([-60,60])
    ax.set_ylabel('Latitude')
    ax.set_xticks([12,24,36,48,60,72])
    ax.set_yticks([-60,-30,0,30,60])
    ax.set_xlabel('Pentad')
    ax.grid(True,linestyle=':')
    
    #originalSize = get(gca, 'Position')
    #set(f1, 'Position', originalSize)
    
    #plt.subplots_adjust(left=0.15, right=0.95, top=0.95, bottom=0.05)
    
    box = ax.get_position()
    #ax.set_position([box.x0*1.05, box.y0, box.width, box.height])
    
    axColor = plt.axes([box.x0 + box.width*0.92, box.y0+box.y0*0.12, 0.015, box.height])
    
    #cb1=fig.colorbar(f1, ax=ax, use_gridspec=True, orientation = 'horizontal',fraction=0.15, pad=0.2, aspect=40)
    #cb1=plt.colorbar(f1, ax=axColor, use_gridspec=True, orientation = 'vertical',fraction=0.15, pad=0.05, aspect=30)
    cb1=fig.colorbar(f1, cax=axColor, orientation = 'vertical')
Esempio n. 18
0
def rossby_plot(run,
                ax,
                rot_fac=1.,
                lev=200.,
                type='vor_only',
                plottype='rossby'):
    '''Plot dvordt or 1/vor * dvordt'''

    #Load data
    data = xr.open_dataset('/disca/share/rg419/Data_moist/climatologies/' +
                           run + '.nc')

    #Calculate psi to overplot
    psi = mass_streamfunction(data, a=6376.0e3, dp_in=50.)
    psi /= 1.e9
    psi = make_sym(psi, asym=True)

    # Make precip symmetric and find the precip centroid
    data['precipitation'] = make_sym(data.precipitation)
    data['ucomp'] = make_sym(data.ucomp)
    data['vcomp'] = make_sym(data.vcomp, asym=True)
    data['omega'] = make_sym(data.omega)

    precip_centroid(data)

    # Calculate vorticity
    v_dx = gr.ddx(data.vcomp)  # dvdx
    u_dy = gr.ddy(data.ucomp)  # dudy
    u_dp = gr.ddp(data.ucomp)  # dudp
    omega = 7.2921150e-5 * rot_fac
    f = 2 * omega * np.sin(data.lat * np.pi / 180)
    vor = (v_dx - u_dy).sel(pfull=lev)
    metric = (data.ucomp / mc.a *
              np.tan(data.lat * np.pi / 180)).sel(pfull=lev)
    vertical_term = (-1. * data.omega / data.vcomp * u_dp).sel(pfull=lev)
    #vor = make_sym(vor, asym=True)
    #metric = make_sym(metric, asym=True)
    #vertical_term = make_sym(vertical_term, asym=True)
    if type == 'vor_only':
        rossby = (-1. * vor / f).mean('lon')
    elif type == 'metric':
        rossby = (-1. * (metric + vor) / f).mean('lon')
    elif type == 'vertical':
        rossby = (-1. * (vor + vertical_term) / f).mean('lon')
    elif type == 'full':
        rossby = (-1. * (metric + vor + vertical_term) / f).mean('lon')
    levels = np.arange(-0.9, 1.0, 0.3)
    if plottype == 'drodt':
        rossby = gr.ddt(rossby) * 84600.
        levels = np.arange(-0.1, 0.1, 0.01)
    f1 = rossby.plot.contourf(ax=ax,
                              x='xofyear',
                              y='lat',
                              levels=levels,
                              add_colorbar=False,
                              add_labels=False,
                              extend='both')
    psi.sel(pfull=lev).plot.contour(ax=ax,
                                    x='xofyear',
                                    y='lat',
                                    levels=np.arange(-500., 0., 100.),
                                    add_labels=False,
                                    colors='0.7',
                                    linewidths=2,
                                    linestyles='--')
    psi.sel(pfull=lev).plot.contour(ax=ax,
                                    x='xofyear',
                                    y='lat',
                                    levels=np.arange(0., 510., 100.),
                                    add_labels=False,
                                    colors='0.7',
                                    linewidths=2)
    psi.sel(pfull=lev).plot.contour(ax=ax,
                                    x='xofyear',
                                    y='lat',
                                    levels=np.arange(-1000., 1010., 1000.),
                                    add_labels=False,
                                    colors='0.5',
                                    linewidths=2)
    data.p_cent.plot.line(ax=ax, color='k', linewidth=2)
    ax.set_ylim([-30, 30])
    ax.set_ylabel('Latitude')
    ax.set_xticks([12, 24, 36, 48, 60, 72])
    ax.set_yticks([-30, -15, 0, 15, 30])
    ax.set_xlabel('Pentad')
    ax.grid(True, linestyle=':')

    #plt.subplots_adjust(left=0.15, right=0.95, top=0.95, bottom=0.05)
    cb1 = fig.colorbar(f1,
                       ax=ax,
                       use_gridspec=True,
                       orientation='horizontal',
                       fraction=0.15,
                       pad=0.2,
                       aspect=40)
    cb1.set_label('Rossby number')
Esempio n. 19
0
def evap_parts(run, lonin=[-1.,361.], do_make_sym=True):
    
    rcParams['figure.figsize'] = 6, 9
    rcParams['font.size'] = 16
    
    plot_dir = '/scratch/rg419/plots/surface_fluxes/'
    mkdir = sh.mkdir.bake('-p')
    mkdir(plot_dir)
    
    data = xr.open_dataset('/scratch/rg419/Data_moist/climatologies/' + run + '.nc')
    
    lons = pick_lons(data, lonin)
    
    # Absolute wind mag, including 1m/s vertical gust
    v_a = np.sqrt(data.ucomp_sq.sel(pfull=950.) + data.vcomp_sq.sel(pfull=950.) + 1.)
    
    # Density of lowest level air
    rho_a = 95000./Rd/data.temp.sel(pfull=950.) / (1 + (Rv - Rd)/Rd*data.sphum.sel(pfull=950.))
    
    # difference between lowest level and surface specific humidities
    q_s = Rd/Rv * 610.78/100000. * np.exp(-L/Rv * (1/data.temp.sel(pfull=950.) - 1/273.16))
    
    # Look at an average over a zonal region
    v_a = v_a.sel(lon=lons).mean('lon')
    rho_a = rho_a.sel(lon=lons).mean('lon')
    q_a = data.sphum.sel(pfull=950.).sel(lon=lons).mean('lon')
    q_s = q_s.sel(lon=lons).mean('lon')
    
    qdiff = (q_a-q_s)*1000.
    
    #(v_a*qdiff).plot.contourf(x='xofyear', y='lat', levels=np.arange(-0.05,0.05,0.005))
    #plt.show()
    #q_a.plot.contourf(x='xofyear', y='lat', levels=np.arange(0,0.02,0.001))
    #plt.figure(2)
    #q_s.plot.contourf(x='xofyear', y='lat', levels=np.arange(0,0.02,0.001))
    #plt.show()
    
    if do_make_sym:
        qdiff = make_sym(qdiff)
        rho_a = make_sym(rho_a)
        v_a = make_sym(v_a)
    
    f, (ax1, ax2, ax3) = plt.subplots(3, sharex=True)

    
    qdiff.plot.contourf(x='xofyear', y='lat', levels=np.arange(-4.5,4.6,0.5), ax=ax1, extend = 'both', add_labels=False)
    ax1.set_title('q$_{a}$ - q$_{s}$')
    
    rho_a.plot.contourf(x='xofyear', y='lat', levels=np.arange(1.,1.41,0.01), ax=ax2, extend = 'both', add_labels=False)
    ax2.set_title('rho$_{a}$')
    
    v_a.plot.contourf(x='xofyear', y='lat', levels=np.arange(0.,20.,2.),  ax=ax3, extend = 'both', add_labels=False)
    ax3.set_title('v$_{a}$')
    
    for ax in [ax1,ax2,ax3]:
        ax.set_ylim([-60,60])
        ax.set_yticks([-60,-30,0,30,60])
        ax.set_ylabel('Latitude')
        ax.grid(True,linestyle=':')
    ax3.set_xticks([12,24,36,48,60,72])
    ax3.set_xlabel('Pentad')
    
    plt.subplots_adjust(left=0.15, right=0.95, top=0.95, bottom=0.1)

    plt.savefig(plot_dir + 'evap_parts_' + run + '.pdf', format='pdf')
    plt.close()
Esempio n. 20
0
        ]
    else:
        lons = [
            data.lon[i] for i in range(len(data.lon))
            if data.lon[i] >= lonin[0] or data.lon[i] < lonin[1]
        ]
    return lons


plot_dir = '/scratch/rg419/plots/itcz_plots/'
mkdir = sh.mkdir.bake('-p')
mkdir(plot_dir)

data = xr.open_dataset(
    '/disca/share/rg419/Data_moist/climatologies/half_shallow.nc')
data['precipitation'] = make_sym(data.precipitation) * 86400.
data_gpcp = xr.open_dataset(
    '/scratch/rg419/obs_and_reanalysis/gpcp_detrendedpentads.nc')
data_gpcp = data_gpcp.rename({'precip_clim': 'precipitation'})

mn_dic = month_dic(1)
tickspace = [13, 31, 49, 68]
labels = ['Mar', 'Jun', 'Sep', 'Dec']

# Set figure parameters
rcParams['figure.figsize'] = 15, 6
rcParams['font.size'] = 16

# Start figure with 6 subplots
fig, ((ax1, ax2, ax3), (ax4, ax5, ax6)) = plt.subplots(2,
                                                       3,
Esempio n. 21
0
def surface_plot(run,
                 lonin=[-1., 361.],
                 diff_run=None,
                 scale_fac=1.,
                 do_make_sym=True):

    print('what?')
    rcParams['figure.figsize'] = 15, 10
    rcParams['font.size'] = 14

    plot_dir = '/scratch/rg419/plots/surface_fluxes/'
    mkdir = sh.mkdir.bake('-p')
    mkdir(plot_dir)

    data = xr.open_dataset('/disca/share/rg419/Data_moist/climatologies/' +
                           run + '.nc')

    #Calculate psi to overplot
    psi = mass_streamfunction(data, a=6376.0e3, dp_in=50.)
    psi /= 1.e9
    psi = make_sym(psi, asym=True)

    # Make precip symmetric and find the precip centroid
    data['precipitation'] = make_sym(data.precipitation)
    precip_centroid(data)

    data['flux_lw_up'] = data.t_surf**4. * mc.stefan
    data['dTdt'] = gr.ddt(data.t_surf) * 86400. * scale_fac

    if do_make_sym:
        for field in [
                't_surf', 'dTdt', 'flux_sw', 'flux_lw', 'flux_lw_up', 'flux_t',
                'flux_lhe'
        ]:
            data[field] = make_sym(data[field])

    lons = pick_lons(data, lonin)

    if not diff_run == None:
        diff_data = xr.open_dataset(
            '/disca/share/rg419/Data_moist/climatologies/' + diff_run + '.nc')
        data = (data - diff_data).sel(lon=lons).mean('lon')
        levels_t = np.arange(-10., 11., 1.)
        levels_dt = np.arange(-0.5, 0.51, 0.05)
        levels_flux = np.arange(-80., 81., 5.)
    else:
        data = data.sel(lon=lons).mean('lon')
        levels_t = np.arange(270., 306., 2.5)
        levels_dt = np.arange(-0.3, 0.31, 0.05)
        levels_flux = np.arange(-300., 305., 20.)

    f, ((ax1, ax2), (ax3, ax4), (ax5, ax6)) = plt.subplots(3,
                                                           2,
                                                           sharex='col',
                                                           sharey='row')
    left_column = [ax1, ax3, ax5]
    bottom_row = [ax5, ax6]
    all_plots = [ax1, ax2, ax3, ax4, ax5, ax6]

    #check = data.flux_sw + (data.flux_lw - flux_lw_up) - data.flux_t - data.flux_lhe
    #check = data.flux_sw - data.flux_lhe

    data.t_surf.plot.contourf(x='xofyear',
                              y='lat',
                              levels=levels_t,
                              ax=ax1,
                              extend='both',
                              add_labels=False)
    ax1.set_title('SST')

    data.dTdt.plot.contourf(x='xofyear',
                            y='lat',
                            ax=ax2,
                            levels=levels_dt,
                            extend='both',
                            add_labels=False,
                            cmap='RdBu_r')
    ax2.set_title('d(SST)/dt')

    data.flux_sw.plot.contourf(x='xofyear',
                               y='lat',
                               levels=levels_flux,
                               ax=ax3,
                               extend='both',
                               add_labels=False,
                               cmap='RdBu_r')
    ax3.set_title('Net downward SW flux')

    (data.flux_lw - data.flux_lw_up).plot.contourf(x='xofyear',
                                                   y='lat',
                                                   levels=levels_flux,
                                                   ax=ax4,
                                                   extend='both',
                                                   add_labels=False,
                                                   cmap='RdBu_r')
    ax4.set_title('Net downward LW flux')

    (-1. * data.flux_t).plot.contourf(x='xofyear',
                                      y='lat',
                                      levels=levels_flux,
                                      ax=ax5,
                                      extend='both',
                                      add_labels=False,
                                      cmap='RdBu_r')
    #check.plot.contourf(x='xofyear', y='lat', levels=np.arange(-300.,305.,20.), ax=ax5, extend = 'both', add_labels=False, cmap='RdBu_r')
    ax5.set_title('Downward sensible heat flux')

    (-1. * data.flux_lhe).plot.contourf(x='xofyear',
                                        y='lat',
                                        levels=levels_flux,
                                        ax=ax6,
                                        extend='both',
                                        add_labels=False,
                                        cmap='RdBu_r')
    ax6.set_title('Downward latent heat flux')

    i = 0
    labels = ['a)', 'b)', 'c)', 'd)', 'e)', 'f)']
    for ax in all_plots:
        ax.grid(True, linestyle=':')
        ax.set_xticks([12, 24, 36, 48, 60, 72])
        ax.set_ylim([-60, 60])
        ax.set_yticks([-60, -30, 0, 30, 60])
        ax.text(-8, 60., labels[i])
        psi.sel(pfull=500).plot.contour(ax=ax,
                                        x='xofyear',
                                        y='lat',
                                        levels=np.arange(-500., 0., 100.),
                                        add_labels=False,
                                        colors='0.7',
                                        linewidths=2,
                                        linestyles='--')
        psi.sel(pfull=500).plot.contour(ax=ax,
                                        x='xofyear',
                                        y='lat',
                                        levels=np.arange(0., 510., 100.),
                                        add_labels=False,
                                        colors='0.7',
                                        linewidths=2)
        psi.sel(pfull=500).plot.contour(ax=ax,
                                        x='xofyear',
                                        y='lat',
                                        levels=np.arange(-1000., 1010., 1000.),
                                        add_labels=False,
                                        colors='0.5',
                                        linewidths=2)
        data.p_cent.plot.line(ax=ax, color='k', linewidth=2)
        ax.set_ylabel('')
        ax.set_xlabel('')
        i = i + 1

    for ax in left_column:
        ax.set_ylabel('Latitude')
    for ax in bottom_row:
        ax.set_xlabel('Pentad')

    plt.subplots_adjust(left=0.07,
                        right=0.97,
                        top=0.97,
                        bottom=0.05,
                        hspace=0.2,
                        wspace=0.1)

    if lonin == [-1., 361.]:
        if not diff_run == None:
            plt.savefig(plot_dir + 'surface_fluxes_' + run + '_' + diff_run +
                        '.pdf',
                        format='pdf')

        else:
            plt.savefig(plot_dir + 'surface_fluxes_' + run + '.pdf',
                        format='pdf')
    else:
        figname = plot_dir + 'surface_fluxes_' + run + '_' + str(int(
            lonin[0])) + '_' + str(int(lonin[1])) + '.pdf'
        plt.savefig(figname, format='pdf')

    plt.close()
Esempio n. 22
0
def evap_parts(run, lonin=[-1., 361.], do_make_sym=True):

    rcParams['figure.figsize'] = 6, 9
    rcParams['font.size'] = 14

    plot_dir = '/scratch/rg419/plots/surface_fluxes/'
    mkdir = sh.mkdir.bake('-p')
    mkdir(plot_dir)

    data = xr.open_dataset('/disca/share/rg419/Data_moist/climatologies/' +
                           run + '.nc')

    #Calculate psi to overplot
    psi = mass_streamfunction(data, a=6376.0e3, dp_in=50.)
    psi /= 1.e9
    psi = make_sym(psi, asym=True)

    # Make precip symmetric and find the precip centroid
    data['precipitation'] = make_sym(data.precipitation)
    precip_centroid(data)

    lons = pick_lons(data, lonin)

    # Density of lowest level air
    #rho_a = 95000./Rd/data.temp.sel(pfull=950.) / (1 + (Rv - Rd)/Rd*data.sphum.sel(pfull=950.))

    # Look at an average over a zonal region
    v_a = data.wind_speed.sel(lon=lons).mean('lon')
    q_a = data.q_atm.sel(lon=lons).mean('lon')
    q_s = data.q_surf.sel(lon=lons).mean('lon')
    qdiff = (q_a - q_s) * 1000.
    rho_a = data.rho.sel(lon=lons).mean('lon')
    #rho_a.plot.contourf()
    #plt.colorbar()
    #plt.show()
    #(v_a*qdiff).plot.contourf(x='xofyear', y='lat', levels=np.arange(-0.05,0.05,0.005))
    #plt.show()
    #q_a.plot.contourf(x='xofyear', y='lat', levels=np.arange(0,0.02,0.001))
    #plt.figure(2)
    #q_s.plot.contourf(x='xofyear', y='lat', levels=np.arange(0,0.02,0.001))
    #plt.show()

    if do_make_sym:
        qdiff = make_sym(qdiff)
        rho_a = make_sym(rho_a)
        v_a = make_sym(v_a)

    f, (ax1, ax2, ax3) = plt.subplots(3, sharex=True)

    qdiff.plot.contourf(x='xofyear',
                        y='lat',
                        ax=ax1,
                        extend='both',
                        add_labels=False,
                        levels=np.arange(-10., 10.1, 1.))
    ax1.set_title('q$_{a}$ - q$_{s}$')

    rho_a.plot.contourf(x='xofyear',
                        y='lat',
                        ax=ax2,
                        extend='both',
                        add_labels=False,
                        levels=np.arange(1.12, 1.26, 0.01))
    ax2.set_title(r'$\rho_{a}$')

    v_a.plot.contourf(x='xofyear',
                      y='lat',
                      levels=np.arange(0., 20., 2.),
                      ax=ax3,
                      extend='both',
                      add_labels=False)
    ax3.set_title('v$_{a}$')

    labels = ['a)', 'b)', 'c)']
    i = 0
    for ax in [ax1, ax2, ax3]:
        #psi.sel(pfull=500).plot.contour(ax=ax, x='xofyear', y='lat', levels=np.arange(-500.,0.,100.), add_labels=False, colors='0.7', linewidths=2, linestyles='--')
        #psi.sel(pfull=500).plot.contour(ax=ax, x='xofyear', y='lat', levels=np.arange(0.,510.,100.), add_labels=False, colors='0.7', linewidths=2)
        #psi.sel(pfull=500).plot.contour(ax=ax, x='xofyear', y='lat', levels=np.arange(-1000.,1010.,1000.), add_labels=False, colors='0.5', linewidths=2)
        #data.p_cent.plot.line(ax=ax, color='k', linewidth=2)
        #ax.set_xlabel('')
        ax.set_ylim([-60, 60])
        ax.set_yticks([-60, -30, 0, 30, 60])
        ax.set_ylabel('Latitude')
        ax.text(-10, 60., labels[i])
        ax.grid(True, linestyle=':')
        i = i + 1
    ax3.set_xticks([12, 24, 36, 48, 60, 72])
    ax3.set_xlabel('Pentad')

    plt.subplots_adjust(left=0.12, right=0.99, top=0.95, bottom=0.06)

    plt.savefig(plot_dir + 'evap_parts_revisions_' + run + '.pdf',
                format='pdf')
    plt.close()
Esempio n. 23
0
def p_cent_rate_max(runs,
                    do_make_sym=True,
                    months=None,
                    days=None,
                    period_fac=1.):
    # Get the maximum rate of change of the precipitation centroid latitude, and the latitude at which this occurs.

    # Ensure runs is a list not a string
    if not isinstance(runs, list):
        runs = [runs]
    if not isinstance(period_fac, list):
        period_fac = [period_fac] * len(runs)
    # Set up empty lists
    max_rate = []
    max_rate_lat = []
    max_lat = []
    if not do_make_sym:  # If we're not averaging both hemispheres, get southern peak magnitude and location too
        max_rate_s = []
        max_rate_lat_s = []
        max_lat_s = []

    if days == None:
        days = [False] * len(runs)

    j = 0
    for run in runs:
        if months == None:  # If no months provided, look for a climatology
            # Open dataset
            data = xr.open_dataset(
                '/disca/share/rg419/Data_moist/climatologies/' + run + '.nc')
            # Get total precip
            try:
                data[
                    'precipitation'] = data.condensation_rain + data.convection_rain
            except:
                data['precipitation'] = data.precipitation
        else:  # If months are provided, load the data for these, and reshape to years/day of year
            try:  # First make sure months is a list of lists
                len(months[0])
            except:
                months = [months]
            data = precip_load_and_reshape(run,
                                           months=months[j],
                                           period_fac=period_fac[j])
        if do_make_sym:  # If symmetric data is wanted, average over both hemispheres (NB currently only set up for a climatology 2/05/18)
            data['precipitation'] = make_sym(data.precipitation)

        # Locate precipitation centroid
        precip_centroid(data)

        # Get rate of movement of precip centroid
        if days[j]:
            dpcentdt = gr.ddt(data.p_cent, secperunit=86400.) * 86400.
        else:
            dpcentdt = gr.ddt(data.p_cent) * 86400.

        def get_max(
            dpcentdt_pmask,
            sh=False
        ):  # Function to find the maximum ratea and it's latitude and the maximum latitude.
            dpcentdt_max = dpcentdt_pmask.where(
                dpcentdt_pmask == dpcentdt_pmask.max('xofyear'),
                drop=True)  # Find the maximum rate
            numdims = len(
                dpcentdt_max.shape
            )  # Check if this is just 1 year or if it's many years
            if numdims != 1:  # If it's many years, evaluate the metrics for each year
                dpdt_max_temp = []  #First set up empty lists
                pcent_dtmax = []
                pcent_max = []
                for y in range(dpcentdt_max.shape[0]):  # Loop over years
                    if sh:  #If it's the southern hemisphere, look for the min latitude of pcent, and make it positive
                        #data.p_cent.sel(year_no=y).plot()
                        #plt.show()
                        pcent_max.append(
                            -1. * data.p_cent.sel(year_no=y).min('xofyear'))
                    else:  # Otherwise look for the maximum latitude
                        pcent_max.append(
                            data.p_cent.sel(year_no=y).max('xofyear'))
                    # Find the maximum rate for the given year, remove any nans that have been added. If there are multiple values, use the smallest
                    dpdt_max_temp.append(
                        dpcentdt_max[y, :].dropna('xofyear')[0])
                    # Find the location of the max rate for that year
                    pcent_dtmax.append(
                        data.p_cent.sel(
                            year_no=y,
                            xofyear=dpdt_max_temp[y].xofyear.values))
                # Convert all results to datarrays
                pcent_dtmax = xr.DataArray(np.asarray(pcent_dtmax),
                                           coords=[data.year_no.values],
                                           dims=['year_no'])
                dpcentdt_max = xr.DataArray(np.asarray(dpdt_max_temp),
                                            coords=[data.year_no.values],
                                            dims=['year_no'])
                pcent_max = xr.DataArray(np.asarray(pcent_max),
                                         coords=[data.year_no.values],
                                         dims=['year_no'])

            else:  # If it's only 1D
                if len(
                        dpcentdt_max
                ) > 1:  # If there are multiple values for the maximum take the smallest
                    dpcentdt_max = dpcentdt_max[0].expand_dims('xofyear',
                                                               axis=0)
                if sh:  # If it's the southern hemisphere find the min lat of pcent, and make it positive
                    pcent_max = -1. * data.p_cent.min('xofyear')
                else:  # Otherwise find the maximum latitude
                    pcent_max = data.p_cent.max('xofyear')
                pcent_max = np.expand_dims(pcent_max, axis=1)
                pcent_dtmax = data.p_cent.sel(
                    xofyear=dpcentdt_max.xofyear
                )  # Find the location of the preciptiation when the rate is maximum
            return dpcentdt_max, pcent_dtmax, pcent_max

        dpcentdt_ppos = dpcentdt.where(
            data.p_cent >= 0.
        )  # Find precip centroid rate where precip centroid is in the northern hemisphere
        dpcentdt_max, pcent_dtmax, pcent_max = get_max(
            dpcentdt_ppos)  # Get the maximum etc
        max_rate.append(dpcentdt_max)  # Add values to lists for different runs
        max_rate_lat.append(pcent_dtmax)
        max_lat.append(pcent_max)

        if not do_make_sym:
            dpcentdt_pneg = -1. * dpcentdt.where(
                data.p_cent <= 0.
            )  # Find precip centroid rate where precip centroid is in the southern hemisphere, and make poleward positive
            dpcentdt_max_s, pcent_dtmax_s, pcent_max_s = get_max(
                dpcentdt_pneg, sh=True)  # Get the maximum etc
            max_rate_s.append(
                dpcentdt_max_s)  # Add values to lists for different runs
            max_rate_lat_s.append(-1. * pcent_dtmax_s)
            max_lat_s.append(pcent_max_s)

        j = j + 1  # Add 1 to counter to get values for next run

    # Convert all output to xarrays
    if do_make_sym:
        if months == None:
            coords_yrno = ['clim']
        else:
            coords_yrno = data.year_no.values
        max_rate = xr.DataArray(np.asarray(max_rate),
                                coords=[runs, coords_yrno],
                                dims=['run', 'year_no'])
        max_rate_lat = xr.DataArray(np.asarray(max_rate_lat),
                                    coords=[runs, coords_yrno],
                                    dims=['run', 'year_no'])
        max_lat = xr.DataArray(np.asarray(max_lat),
                               coords=[runs, coords_yrno],
                               dims=['run', 'year_no'])

    else:
        if months == None:
            coords_yrno = ['clim']
        else:
            coords_yrno = data.year_no.values
        max_rate = (xr.DataArray(np.asarray([max_rate, max_rate_s]),
                                 coords=[['n', 's'], runs, coords_yrno],
                                 dims=['hemisphere', 'run', 'year_no'
                                       ])).transpose('run', 'year_no',
                                                     'hemisphere')
        max_rate_lat = (xr.DataArray(np.asarray([max_rate_lat,
                                                 max_rate_lat_s]),
                                     coords=[['n', 's'], runs, coords_yrno],
                                     dims=['hemisphere', 'run',
                                           'year_no'])).transpose(
                                               'run', 'year_no', 'hemisphere')
        max_lat = (xr.DataArray(np.asarray([max_lat, max_lat_s]),
                                coords=[['n', 's'], runs, coords_yrno],
                                dims=['hemisphere', 'run', 'year_no'
                                      ])).transpose('run', 'year_no',
                                                    'hemisphere')

    return max_rate, max_rate_lat, max_lat
Esempio n. 24
0
def vdtdy_plot(run, lev=850.):

    data = xr.open_dataset('/disca/share/rg419/Data_moist/climatologies/' + run + '.nc')
    
    psi = mass_streamfunction(data, a=6376.0e3, dp_in=50.)
    psi /= 1.e9
    
    try:
        data['precipitation'] = make_sym(data.precipitation)
    except:
        data['precipitation'] = data.convection_rain + data.condensation_rain
        data['precipitation'] = make_sym(data.precipitation)
    
    precip_centroid(data)
    
    convTtotheta=(1000./data.pfull)**(2./7.)
    
    theta = data.temp*convTtotheta
    #rcParams['figure.figsize'] = 5.5, 4.3
    #theta.mean('lon').sel(xofyear=40).plot.contourf(x='lat', y='pfull', yincrease=False)
    #plt.show()
    dvtdy = -1.*(gr.ddy(data.vcomp * theta)).mean('lon').sel(pfull=lev)*86400.
    dwtdp = -1.*(gr.ddp(data.omega * theta)).mean('lon').sel(pfull=lev)*86400.
    
    adv_tend_grad = gr.ddy(dvtdy+dwtdp, vector=False)*10.**5.
    
    dTdt = (gr.ddt(theta)).mean('lon').sel(pfull=lev)*86400./theta.mean('lon').sel(pfull=lev)
    
    dvtdy_colav = -1.*gr.ddy((data.vcomp * theta).mean('lon').mean('pfull')*5000./9.8)*1004.64
    #dwtdp = -1.*gr.ddp((data.omega * theta).mean('lon').sum('pfull')*50./9.8)
    dTdt_colav = gr.ddt(theta.mean('lon').sum('pfull')*5000./9.8)*1004.64
    
    plot_dir = '/scratch/rg419/plots/paper_2_figs/dvtdy/'
    mkdir = sh.mkdir.bake('-p')
    mkdir(plot_dir)
    
    #rcParams['figure.figsize'] = 5.5, 4.3
    rcParams['figure.figsize'] = 5, 10.5
    rcParams['font.size'] = 14
    #rcParams['font.size'] = 16

    #fig = plt.figure()
    #ax1 = fig.add_subplot(111)    
    fig, ((ax1), (ax2), (ax3)) = plt.subplots(3, 1)
    
    f1 = (dvtdy+dwtdp).plot.contourf(ax=ax1, x='xofyear', y='lat', add_labels=False, levels=np.arange(-50.,55.,5.), extend='both')
    psi.sel(pfull=500).plot.contour(ax=ax1, x='xofyear', y='lat', levels=np.arange(-500.,0.,100.), add_labels=False, colors='0.7', linewidths=2, linestyles='--')
    psi.sel(pfull=500).plot.contour(ax=ax1, x='xofyear', y='lat', levels=np.arange(0.,510.,100.), add_labels=False, colors='0.7', linewidths=2)
    psi.sel(pfull=500).plot.contour(ax=ax1, x='xofyear', y='lat', levels=np.arange(-1000.,1010.,1000.), add_labels=False, colors='0.5', linewidths=2)
    data.p_cent.plot.line(ax=ax1,color='k', linewidth=2)
    ax1.set_ylim([-60,60])
    ax1.set_ylabel('Latitude')
    ax1.set_xticks([12,24,36,48,60,72])
    ax1.set_yticks([-60,-30,0,30,60])
    ax1.set_xlabel('Pentad')
    ax1.grid(True,linestyle=':')
    
    f1 = adv_tend_grad.plot.contourf(ax=ax2, x='xofyear', y='lat', add_labels=False, levels=np.arange(-10.,11.,1.),  extend='both')
    psi.sel(pfull=500).plot.contour(ax=ax2, x='xofyear', y='lat', levels=np.arange(-500.,0.,100.), add_labels=False, colors='0.7', linewidths=2, linestyles='--')
    psi.sel(pfull=500).plot.contour(ax=ax2, x='xofyear', y='lat', levels=np.arange(0.,510.,100.), add_labels=False, colors='0.7', linewidths=2)
    psi.sel(pfull=500).plot.contour(ax=ax2, x='xofyear', y='lat', levels=np.arange(-1000.,1010.,1000.), add_labels=False, colors='0.5', linewidths=2)
    data.p_cent.plot.line(ax=ax2,color='k', linewidth=2)
    ax2.set_ylim([-60,60])
    ax2.set_ylabel('Latitude')
    ax2.set_xticks([12,24,36,48,60,72])
    ax2.set_yticks([-60,-30,0,30,60])
    ax2.set_xlabel('Pentad')
    ax2.grid(True,linestyle=':')
    
    #f1 = dvtdy_colav.plot.contourf(ax=ax3, x='xofyear', y='lat', add_labels=False, levels=np.arange(-50.,51.,5.), extend='both')
    #psi.sel(pfull=500).plot.contour(ax=ax3, x='xofyear', y='lat', levels=np.arange(-500.,0.,100.), add_labels=False, colors='0.7', linewidths=2, linestyles='--')
    #psi.sel(pfull=500).plot.contour(ax=ax3, x='xofyear', y='lat', levels=np.arange(0.,510.,100.), add_labels=False, colors='0.7', linewidths=2)
    #psi.sel(pfull=500).plot.contour(ax=ax3, x='xofyear', y='lat', levels=np.arange(-1000.,1010.,1000.), add_labels=False, colors='0.5', linewidths=2)
    #data.p_cent.plot.line(ax=ax3,color='k', linewidth=2)
    #ax3.set_ylim([-60,60])
    #ax3.set_ylabel('Latitude')
    #ax3.set_xticks([12,24,36,48,60,72])
    #ax3.set_yticks([-60,-30,0,30,60])
    #ax3.set_xlabel('Pentad')
    #ax3.grid(True,linestyle=':')
    
    plt.subplots_adjust(left=0.15, right=0.95, top=0.95, bottom=0.05)

   # cb1=fig.colorbar(f1, ax=ax1, use_gridspec=True, orientation = 'horizontal',fraction=0.15, pad=0.2, aspect=40)
   # cb1.set_label('Advective temperature tendency, Kday$^{-1}$')

    plt.savefig(plot_dir+'adv_tend_' + run + '.pdf', format='pdf')
    plt.close()
Esempio n. 25
0
def surface_plot(run,
                 lonin=[-1., 361.],
                 diff_run=None,
                 scale_fac=1.,
                 do_make_sym=True):

    rcParams['figure.figsize'] = 12, 10
    rcParams['font.size'] = 16

    plot_dir = '/scratch/rg419/plots/surface_fluxes/'
    mkdir = sh.mkdir.bake('-p')
    mkdir(plot_dir)

    data = xr.open_dataset('/scratch/rg419/Data_moist/climatologies/' + run +
                           '.nc')

    data['flux_lw_up'] = data.t_surf**4. * mc.stefan
    data['dTdt'] = gr.ddt(data.t_surf) * 86400. * scale_fac

    if do_make_sym:
        for field in [
                't_surf', 'dTdt', 'flux_sw', 'flux_lw', 'flux_lw_up', 'flux_t',
                'flux_lhe'
        ]:
            data[field] = make_sym(data[field])

    lons = pick_lons(data, lonin)

    if not diff_run == None:
        diff_data = xr.open_dataset(
            '/scratch/rg419/Data_moist/climatologies/' + diff_run + '.nc')
        data = (data - diff_data).sel(lon=lons).mean('lon')
        levels_t = np.arange(-10., 11., 1.)
        levels_dt = np.arange(-0.5, 0.51, 0.05)
        levels_flux = np.arange(-80., 81., 5.)
    else:
        data = data.sel(lon=lons).mean('lon')
        levels_t = np.arange(250., 311., 1.)
        levels_dt = np.arange(-0.5, 0.51, 0.01)
        levels_flux = np.arange(-300., 305., 10.)

    f, ((ax1, ax2), (ax3, ax4), (ax5, ax6)) = plt.subplots(3,
                                                           2,
                                                           sharex='col',
                                                           sharey='row')
    left_column = [ax1, ax3, ax5]
    bottom_row = [ax5, ax6]
    all_plots = [ax1, ax2, ax3, ax4, ax5, ax6]

    #check = data.flux_sw + (data.flux_lw - flux_lw_up) - data.flux_t - data.flux_lhe
    #check = data.flux_sw - data.flux_lhe

    data.t_surf.plot.contourf(x='xofyear',
                              y='lat',
                              levels=levels_t,
                              ax=ax1,
                              extend='both',
                              add_labels=False)
    ax1.set_title('SST')

    data.dTdt.plot.contourf(x='xofyear',
                            y='lat',
                            ax=ax2,
                            levels=levels_dt,
                            extend='both',
                            add_labels=False,
                            cmap='RdBu_r')
    ax2.set_title('d(SST)/dt')

    data.flux_sw.plot.contourf(x='xofyear',
                               y='lat',
                               levels=levels_flux,
                               ax=ax3,
                               extend='both',
                               add_labels=False,
                               cmap='RdBu_r')
    ax3.set_title('Net downward SW flux')

    (data.flux_lw - data.flux_lw_up).plot.contourf(x='xofyear',
                                                   y='lat',
                                                   levels=levels_flux,
                                                   ax=ax4,
                                                   extend='both',
                                                   add_labels=False,
                                                   cmap='RdBu_r')
    ax4.set_title('Net downward LW flux')

    (-1. * data.flux_t).plot.contourf(x='xofyear',
                                      y='lat',
                                      levels=levels_flux,
                                      ax=ax5,
                                      extend='both',
                                      add_labels=False,
                                      cmap='RdBu_r')
    #check.plot.contourf(x='xofyear', y='lat', levels=np.arange(-300.,305.,20.), ax=ax5, extend = 'both', add_labels=False, cmap='RdBu_r')
    ax5.set_title('Downward sensible heat flux')

    (-1. * data.flux_lhe).plot.contourf(x='xofyear',
                                        y='lat',
                                        levels=levels_flux,
                                        ax=ax6,
                                        extend='both',
                                        add_labels=False,
                                        cmap='RdBu_r')
    ax6.set_title('Downward latent heat flux')

    for ax in left_column:
        ax.set_ylabel('Latitude')
    for ax in bottom_row:
        ax.set_xlabel('Pentad')
    for ax in all_plots:
        ax.grid(True, linestyle=':')
        ax.set_xticks([12, 24, 36, 48, 60, 72])
        ax.set_ylim([-60, 60])

    if not diff_run == None:
        plt.savefig(plot_dir + 'surface_fluxes_' + run + '_' + diff_run +
                    '.pdf',
                    format='pdf')

    else:
        plt.savefig(plot_dir + 'surface_fluxes_' + run + '.pdf', format='pdf')
    plt.close()