Beispiel #1
0
def plotWinds(u_snd, v_snd, p_snd, **kwargs):
    t_base = 45
    stride = 1

    idx_min = np.argmin(np.abs(_p_max - p_snd))
    idx_max = np.argmin(np.abs(_p_min - p_snd))

    if p_snd[idx_min] > _p_max:
        idx_min += 1

    if p_snd[idx_max] > _p_min:
        idx_max += 1

    thin_data = (slice(idx_min, idx_max, stride))
    pylab.axvline(x=t_base, color='k', lw=0.5)

    points = np.vstack((t_base * np.ones(p_snd.shape), p_snd)).T

    x, base_y = _stlp_data_transform.transform(np.array([[t_base, 1000]]))[0]
    trans_points = _stlp_data_transform.transform(points)
    trans_points[:, 0] = x

    axes_points = pylab.gca().transData.inverted().transform(trans_points)

    plot_xs, plot_ys = zip(*axes_points)
    pylab.barbs(plot_xs[thin_data], plot_ys[thin_data], u_snd[thin_data], v_snd[thin_data], clip_on=False)
    return
def plot_ua_rhum(press):
    print("    %smb RHUM" % press)
    level = levid[str(press)]

    #Set Figure Size (1000 x 800)
    pylab.figure(figsize=(width, height), frameon=False)
    heights = hght_clevs[contlevid[str(press)]]

    cdict = {
        'red': ((0.00, 0.76, 0.76), (0.25, 0.64, 0.64), (0.50, 0.52, 0.52),
                (0.75, 0.42, 0.42), (1.00, 0.32, 0.32)),
        'green': ((0.00, 0.90, 0.90), (0.25, 0.80, 0.80), (0.50, 0.70, 0.70),
                  (0.75, 0.60, 0.60), (1.00, 0.50, 0.50)),
        'blue': ((0.00, 0.49, 0.49), (0.25, 0.32, 0.32), (0.50, 0.17, 0.17),
                 (0.75, 0.06, 0.06), (1.00, 0.05, 0.05))
    }

    rhum_coltbl = LinearSegmentedColormap('RHUM_COLTBL', cdict)

    # Temperature calculation here

    #TC = temps_ua[time,level] - 273
    TH_K = np.add(temps_ua[time, level], temps_base_ua)
    TK = np.multiply(TH_K, math.pow((float(press) / 1000.), (287.04 / 1004.)))
    TC = TK - 273

    # RHUM Calculation here
    es = 6.112 * np.exp(17.67 * TC / (TC + 243.5))
    w = np.divide(qvap[time, level], (1 - qvap[time, level]))
    e = (w * float(press)) / (0.622 + w)
    relh = e / es * 100.

    RHUM = pylab.contourf(x,
                          y,
                          relh,
                          rhum_clevs,
                          extend='max',
                          cmap=rhum_coltbl)

    # Contour the heights

    phtotal = np.add(phb[time, level], ph[time, level])
    gheight = np.divide(phtotal, 9.81)
    #gheight = ght[time,level]
    HGHT = pylab.contour(x, y, gheight, heights, colors='k', linewidths=1.5)
    pylab.clabel(HGHT, inline=1, fontsize=8, fmt='%1.0f', inline_spacing=1)

    # Convert winds from m/s to kts and then draw barbs
    u_wind_kts = u_wind_ms_ua[time, level] * 1.94384449
    v_wind_kts = v_wind_ms_ua[time, level] * 1.94384449


    pylab.barbs(x_th,y_th,u_wind_kts[::thin,::thin],\
     v_wind_kts[::thin,::thin], length=5, sizes={'spacing':0.2},pivot='middle')

    title = '%s mb RELH, Height (m), Wind (kts)' % press
    prodid = '%smb_rel_hum' % press
    units = "percent"

    drawmap(RHUM, title, prodid, units)
def plot_ua_vvel(press):
    print("    %smb VVEL" % press)
    level = levid[str(press)]

    #Set Figure Size (1000 x 800)
    pylab.figure(figsize=(width, height), frameon=False)

    cdict_vvel = {
        'red': ((0.00, 0.50, 0.50), (0.10, 1.00, 1.00), (0.20, 1.00, 1.00),
                (0.35, 1.00, 1.00), (0.40, 1.00, 1.00), (0.45, 0.80, 0.80),
                (0.50, 0.72, 0.72), (0.55, 0.68, 0.68), (0.60, 0.64, 0.64),
                (0.65, 0.60, 0.70), (0.70, 0.40, 0.45), (0.80, 0.20, 0.20),
                (0.90, 0.00, 0.00), (1.00, 0.00, 0.00)),
        'green': ((0.00, 0.35, 0.35), (0.10, 0.45, 0.45), (0.20, 0.55, 0.55),
                  (0.35, 1.00, 1.00), (0.40, 1.00, 1.00), (0.45, 1.00, 1.00),
                  (0.50, 1.00, 1.00), (0.55, 1.00, 1.00), (0.60, 1.00, 1.00),
                  (0.65, 1.00, 1.00), (0.70, 1.00, 1.00), (0.80, 1.00, 1.00),
                  (0.90, 1.00, 1.00), (1.00, 0.80, 0.80)),
        'blue': ((0.00, 0.00, 0.00), (0.10, 0.00, 0.00), (0.20, 0.20, 0.20),
                 (0.35, 1.00, 1.00), (0.40, 1.00, 1.00), (0.45, 1.00, 1.00),
                 (0.50, 1.00, 1.00), (0.55, 1.00, 1.00), (0.60, 1.00, 1.00),
                 (0.65, 1.00, 1.00), (0.70, 1.00, 1.00), (0.80, 1.00, 1.00),
                 (0.90, 1.00, 1.00), (1.00, 0.80, 0.80))
    }

    vvel_coltbl = LinearSegmentedColormap('VVEL_COLTBL', cdict_vvel)

    vert_vel = np.multiply(w_wind_ua[time, level], 100)
    vert_vel = np.nan_to_num(vert_vel)

    VVEL = pylab.contourf(x,
                          y,
                          vert_vel,
                          vvel_clevs,
                          cmap=vvel_coltbl,
                          extend='both')

    # Contour the heights

    heights = hght_clevs[contlevid[str(press)]]
    phtotal = np.add(phb[time, level], ph[time, level])
    gheight = np.divide(phtotal, 9.81)
    #gheight = ght[time,level]

    HGHT = pylab.contour(x, y, gheight, heights, colors='k', linewidths=1.5)
    pylab.clabel(HGHT, inline=1, fontsize=8, fmt='%1.0f', inline_spacing=1)

    # Convert winds from m/s to kts and then draw barbs
    u_wind_kts = u_wind_ms_ua[time, level] * 1.94384449
    v_wind_kts = v_wind_ms_ua[time, level] * 1.94384449


    pylab.barbs(x_th,y_th,u_wind_kts[::thin,::thin],\
     v_wind_kts[::thin,::thin], length=5, sizes={'spacing':0.2},pivot='middle')

    title = '%s mb VVel, Height (m), Wind (kts)' % press
    prodid = '%smb_vert_vel' % press
    units = "cm/s"

    drawmap(VVEL, title, prodid, units)
Beispiel #4
0
def plotObservations(obs, map, title, file_name, refl=None):
    pylab.clf()

    if refl is not None:
        nx, ny = refl.shape
        xs, ys = np.meshgrid(np.arange(nx) * 1000, np.arange(ny) * 1000)
        map.contour(xs, ys, refl, levels=np.arange(20, 80, 20), colors='k')

    obs_x, obs_y = map(obs['longitude'], obs['latitude'])

    for ob, x, y in zip(obs, obs_x, obs_y):
        pylab.plot(x, y, 'ko', ms=3.)
        pylab.text(x - 500, y + 500, "%4.1f" % ob['temp'], size='small', va='bottom', ha='right', color='r') 
        pylab.text(x - 500, y - 500, "%4.1f" % ob['dewp'], size='small', va='top', ha='right', color='g') 
        pylab.text(x + 500, y - 500, ob['id'], size='small', va='top', ha='left', color='#808080')

    good_idxs = np.where((obs['wind_spd'] >= 0.) & (obs['wind_dir'] >= 0.))

    u = -obs['wind_spd'] * np.sin(obs['wind_dir'] * np.pi / 180) * 1.94
    v = -obs['wind_spd'] * np.cos(obs['wind_dir'] * np.pi / 180) * 1.94
    u_rot, v_rot = map.rotate_vector(u, v, obs['longitude'], obs['latitude'])
    pylab.barbs(obs_x[good_idxs], obs_y[good_idxs], u_rot[good_idxs], v_rot[good_idxs])

    drawPolitical(map, scale_len=5)

    pylab.title(title)
    pylab.savefig(file_name)
    return
Beispiel #5
0
def plot_sfwind():
	print("    10M WIND")
	# Set Figure Size (1000 x 800)
	pylab.figure(figsize=(width,height),frameon=False)

	# Convert winds from m/s to kts and then draw barbs	
	u_wind_kts = u_wind_ms[time] * 1.94384449
	v_wind_kts = v_wind_ms[time] * 1.94384449
	windmag = np.power(np.power(u_wind_kts,2)+np.power(v_wind_kts,2), 0.5)
	WIND_LEVS = range(10,46,2)
	W=pylab.contourf(x,y,windmag,WIND_LEVS,extend='max')

	pylab.barbs(x_th,y_th,u_wind_kts[::thin,::thin],\
		v_wind_kts[::thin,::thin], length=5,\
		sizes={'spacing':0.2},pivot='middle')



	# Convert Surface Pressure to Mean Sea Level Pressure	
	stemps = temps[time]+6.5*nc.variables['HGT'][time]/1000.
	mslp = nc.variables['PSFC'][time]*np.exp(9.81/(287.0*stemps)*nc.variables['HGT'][time])*0.01 + (6.7 * nc.variables['HGT'][time] / 1000)

	# Contour the pressure
	#PLEVS = range(900,1050,5)
	#P=pylab.contour(x,y,mslp,PLEVS,V=2,colors='k',linewidths=1.5)
	#pylab.clabel(P,inline=1,fontsize=8,fmt='%1.0f',inline_spacing=1)



	title = 'Sfc MSLP (mb), 10m Wind (kts)'
	prodid = 'wind'
	units = "kts"	

	drawmap(W, title, prodid, units)
Beispiel #6
0
def plot_srhel():
	print("    SR Helicity")
	# Set Figure Size (1000 x 800)
	pylab.figure(figsize=(width,height),frameon=False)
	P = nc.variables['P']
	PB = nc.variables['PB']
	UU = nc.variables['U']
	VV = nc.variables['V']
	PH = nc.variables['PH']
	PHB = nc.variables['PHB']

	# Need pressures, temps and mixing ratios
	PR = P[time] + PB[time]
	PHT = np.add(PH[time],PHB[time])
	ZH = np.divide(PHT, 9.81)
	U = UU[time]
	V = VV[time]
	

	for j in range(len(U[1,:,1])):
		curcol_c = []
		curcol_Umo = []
		curcol_Vmo = []
		for i in range(len(V[1,1,:])):
				sparms = severe.SRHEL_CALC(U[:,j,i], V[:,j,i], ZH[:,j,i], PR[:,j,i])
				curcol_c.append(sparms[0])		
				curcol_Umo.append(sparms[1])
				curcol_Vmo.append(sparms[2])
		np_curcol_c = np.array(curcol_c)
		np_curcol_Umo = np.array(curcol_Umo)
		np_curcol_Vmo = np.array(curcol_Vmo)

		if j == 0:
			srhel = np_curcol_c
			U_srm = np_curcol_Umo
			V_srm = np_curcol_Vmo
		else:
			srhel = np.row_stack((srhel, np_curcol_c))
			U_srm = np.row_stack((U_srm, np_curcol_Umo))
			V_srm = np.row_stack((V_srm, np_curcol_Vmo))

	#print "       SRHEL: ", np.shape(srhel)

	# Now plot
	SRHEL_LEVS = range(50,800,50)
	srhel = np.nan_to_num(srhel)
	SRHEL=pylab.contourf(x,y,srhel,SRHEL_LEVS)

	u_mo_kts = U_srm * 1.94384449
	v_mo_kts = V_srm * 1.94384449
	pylab.barbs(x_th,y_th,u_mo_kts[::thin,::thin],\
		v_mo_kts[::thin,::thin], length=5,\
		sizes={'spacing':0.2},pivot='middle')
	title = '0-3 km SRHelicity, Storm Motion (kt)'
	prodid = 'hlcy'
	units = "m" + u'\u00B2' + '/s' + u'\u00B2'

	drawmap(SRHEL, title, prodid, units) 	
Beispiel #7
0
def _windbarbs(speed, theta, p):  # in kt
    x = np.cos(np.radians(270 - theta))  # direction only
    y = np.sin(np.radians(270 - theta))  # direction only
    u = x * speed
    v = y * speed

    for item in zip(p, theta, speed, x, y, u, v):
        print(item)

    i = 0
    for pi in p * 100:
        pl.barbs(45, pi, u[i], v[i])
        i = i + 1

    return
Beispiel #8
0
def plotObservations(obs, map, title, file_name, refl=None):
    pylab.clf()

    if refl is not None:
        nx, ny = refl.shape
        xs, ys = np.meshgrid(np.arange(nx) * 1000, np.arange(ny) * 1000)
        map.contour(xs, ys, refl, levels=np.arange(20, 80, 20), colors='k')

    obs_x, obs_y = map(obs['longitude'], obs['latitude'])

    for ob, x, y in zip(obs, obs_x, obs_y):
        pylab.plot(x, y, 'ko', ms=3.)
        pylab.text(x - 500,
                   y + 500,
                   "%4.1f" % ob['temp'],
                   size='small',
                   va='bottom',
                   ha='right',
                   color='r')
        pylab.text(x - 500,
                   y - 500,
                   "%4.1f" % ob['dewp'],
                   size='small',
                   va='top',
                   ha='right',
                   color='g')
        pylab.text(x + 500,
                   y - 500,
                   ob['id'],
                   size='small',
                   va='top',
                   ha='left',
                   color='#808080')

    good_idxs = np.where((obs['wind_spd'] >= 0.) & (obs['wind_dir'] >= 0.))

    u = -obs['wind_spd'] * np.sin(obs['wind_dir'] * np.pi / 180) * 1.94
    v = -obs['wind_spd'] * np.cos(obs['wind_dir'] * np.pi / 180) * 1.94
    u_rot, v_rot = map.rotate_vector(u, v, obs['longitude'], obs['latitude'])
    pylab.barbs(obs_x[good_idxs], obs_y[good_idxs], u_rot[good_idxs],
                v_rot[good_idxs])

    drawPolitical(map, scale_len=5)

    pylab.title(title)
    pylab.savefig(file_name)
    return
Beispiel #9
0
def plotWinds(u_snd, v_snd, p_snd, **kwargs):
    t_base = 45
    stride = 50
    thin_data = (slice(None, None, stride))
    pylab.axvline(x=t_base, color='k', lw=0.5)

    points = np.vstack((t_base * np.ones(p_snd.shape), p_snd)).T

    x, base_y = _stlp_data_transform.transform(np.array([[t_base, 1000]]))[0]
    trans_points = _stlp_data_transform.transform(points)
    trans_points[:, 0] = x

    axes_points = pylab.gca().transData.inverted().transform(trans_points)

    plot_xs, plot_ys = zip(*axes_points)
    pylab.barbs(plot_xs[thin_data], plot_ys[thin_data], u_snd[thin_data], v_snd[thin_data])
    return
def plot_ua_winds(press):
    from scipy.ndimage.filters import gaussian_filter
    print("    %smb WINDS" % press)
    level = levid[str(press)]

    #Set Figure Size (1000 x 800)
    pylab.figure(figsize=(width, height), frameon=False)
    heights = hght_clevs[contlevid[str(press)]]

    phtotal = np.add(phb[time, level], ph[time, level])
    gheight = gaussian_filter(np.divide(phtotal, 9.81), 1)
    #gheight = np.divide(phtotal, 9.81)
    #gheight = ght[time,level]

    # Convert winds from m/s to kts and then draw barbs
    u_wind_kts = u_wind_ms_ua[time, level] * 1.94384449
    v_wind_kts = v_wind_ms_ua[time, level] * 1.94384449

    u_wind_kts_sq = np.power(u_wind_kts, 2)
    v_wind_kts_sq = np.power(v_wind_kts, 2)
    wind_sum = np.add(u_wind_kts_sq, v_wind_kts_sq)
    # Find actual wind speed and contour
    windspd = np.sqrt(wind_sum)
    WSPD = pylab.contourf(x,
                          y,
                          windspd,
                          wspd_clevs[contlevid[str(press)]],
                          extend='max')

    # Contour the heights

    HGHT = pylab.contour(x, y, gheight, heights, linewidths=1.5, colors='k')
    pylab.clabel(HGHT, inline=1, fontsize=8, fmt='%1.0f', inline_spacing=1)

    #pylab.clabel(T,inline=1,fontsize=10)


    pylab.barbs(x_th,y_th,u_wind_kts[::thin,::thin],\
     v_wind_kts[::thin,::thin], length=5, sizes={'spacing':0.2},pivot='middle')

    title = '%s mb Height (m), Wind' % press
    prodid = '%smb_wind' % press
    units = 'kts'

    drawmap(WSPD, title, prodid, units)
Beispiel #11
0
def plotWinds(u_snd, v_snd, p_snd, **kwargs):
    t_base = 45
    stride = 50
    thin_data = (slice(None, None, stride))
    pylab.axvline(x=t_base, color='k', lw=0.5)

    points = np.vstack((t_base * np.ones(p_snd.shape), p_snd)).T

    x, base_y = _stlp_data_transform.transform(np.array([[t_base, 1000]]))[0]
    trans_points = _stlp_data_transform.transform(points)
    trans_points[:, 0] = x

    axes_points = pylab.gca().transData.inverted().transform(trans_points)

    plot_xs, plot_ys = zip(*axes_points)
    pylab.barbs(plot_xs[thin_data], plot_ys[thin_data], u_snd[thin_data],
                v_snd[thin_data])
    return
Beispiel #12
0
def plot_dwp():
	print "    DEWPOINT"
	# Set Figure Size (1000 x 800)
	pylab.figure(figsize=(width,height),frameon=False)
	qhum = nc.variables['Q2']
	
	
	# Convert Surface Pressure to Mean Sea Level Pressure
	stemps = temps[time]+6.5*nc.variables['HGT'][time]/1000.
	mslp = psfc[time]*np.exp(9.81/(287.0*stemps)*nc.variables['HGT'][time])*0.01
	# Find saturation vapor pressure
	es = 6.112 * np.exp(17.67 * temps[time]/(temps[time] + 243.5))
	w = qhum[time]/(1-qhum[time])
	e = (w * psfc[time] / (.622 + w)) / 100
	Td_C = (243.5 * np.log(e/6.112))/(17.67-np.log(e/6.112))
	Td_F = (Td_C * 9 / 5) + 32


	DP_LEVS = range(-10,85,1)

	# Contour and fill the dewpoint temperature		
	Td=pylab.contourf(x,y,Td_F,DP_LEVS,cmap=coltbls.dewpoint1(),extend='min')
	Td_lev = pylab.contour(x,y,Td_F,DP_CLEVS,colors='k',linewidths=.5)
	pylab.clabel(Td_lev,inline=1,fontsize=7,fmt='%1.0f',inline_spacing=1)

	# Contour the pressure
	# P=pylab.contour(x,y,mslp,V=2,colors='k',linewidths=1.5)
	# pylab.clabel(P,inline=1,fontsize=8,fmt='%1.0f',inline_spacing=1)

	#pylab.clabel(T,inline=1,fontsize=10)

	# Convert winds from m/s to kts and then draw barbs	
	u_wind_kts = u_wind_ms[time] * 1.94384449
	v_wind_kts = v_wind_ms[time] * 1.94384449
	pylab.barbs(x_th,y_th,u_wind_kts[::thin,::thin],\
		v_wind_kts[::thin,::thin], length=5,\
		sizes={'spacing':0.2},pivot='middle')

	title = 'Surface Dwp, 10m Wind (kts)'
	prodid = 'dewp'
	units = u"\u00B0" + "F"	

	drawmap(Td, title, prodid, units)
def plot_ua_winds(press):
	from scipy.ndimage.filters import gaussian_filter
	print("    %smb WINDS" % press)
	level = levid[str(press)]

	#Set Figure Size (1000 x 800)
	pylab.figure(figsize=(width,height),frameon=False)
	heights=hght_clevs[contlevid[str(press)]]
	
	phtotal = np.add(phb[time,level],ph[time,level])
	gheight = gaussian_filter(np.divide(phtotal, 9.81),1)
	#gheight = np.divide(phtotal, 9.81)
	#gheight = ght[time,level]

	# Convert winds from m/s to kts and then draw barbs	
	u_wind_kts = u_wind_ms_ua[time,level] * 1.94384449
	v_wind_kts = v_wind_ms_ua[time,level] * 1.94384449
	
	u_wind_kts_sq = np.power(u_wind_kts, 2)
	v_wind_kts_sq = np.power(v_wind_kts, 2)
	wind_sum = np.add(u_wind_kts_sq,v_wind_kts_sq)
	# Find actual wind speed and contour
	windspd = np.sqrt(wind_sum)
	WSPD=pylab.contourf(x,y,windspd,wspd_clevs[contlevid[str(press)]],extend='max')

	# Contour the heights

	HGHT=pylab.contour(x,y,gheight,heights,linewidths=1.5, colors = 'k')
	pylab.clabel(HGHT,inline=1,fontsize=8,fmt='%1.0f',inline_spacing=1)

	#pylab.clabel(T,inline=1,fontsize=10)


	pylab.barbs(x_th,y_th,u_wind_kts[::thin,::thin],\
		v_wind_kts[::thin,::thin], length=5, sizes={'spacing':0.2},pivot='middle')

	title = '%s mb Height (m), Wind' % press
	prodid = '%smb_wind' % press
	units = 'kts'

	drawmap(WSPD, title, prodid, units)
Beispiel #14
0
def plot_thte():
	"""Plot surface theta-e map"""
	print "    THETA-E"
	pylab.figure(figsize=(width,height),frameon=False)
	qhum = nc.variables['Q2']

	thte = (temps[time] + qhum[time] * 2500000.0/1004.0) * (100000/psfc[time]) ** (287.0/1004.0) 	
	THTE_LEVS = range(270,360,5)
	THTE = pylab.contourf(x,y,thte,THTE_LEVS,cmap=coltbls.thetae(),extend='max')

	u_wind_kts = u_wind_ms[time] * 1.94384449
	v_wind_kts = v_wind_ms[time] * 1.94384449
	pylab.barbs(x_th,y_th,u_wind_kts[::thin,::thin],\
		v_wind_kts[::thin,::thin], length=5,\
		sizes={'spacing':0.2},pivot='middle')

	title = 'Theta-e, 10 m Wind (kt)'
	prodid = 'thte'
	units = 'K'

	drawmap(THTE, title, prodid, units)
def plot_ua_temps(press):
    print("    %smb TEMPERATURE" % press)
    level = levid[str(press)]
    #Set Figure Size (1000 x 800)
    pylab.figure(figsize=(width, height), frameon=False)
    heights = hght_clevs[contlevid[str(press)]]

    # Temperature calculation here

    #TC = temps_ua[time,level] - 273
    TH_K = np.add(temps_ua[time, level], temps_base_ua)
    TK = np.multiply(TH_K, math.pow((float(press) / 1000.), (287.04 / 1004.)))
    TC = TK - 273
    TEMP = pylab.contourf(x,
                          y,
                          TC,
                          temp_clevs[contlevid[str(press)]],
                          extend='both')

    # Contour the heights

    phtotal = np.add(phb[time, level], ph[time, level])
    gheight = np.divide(phtotal, 9.81)
    #gheight = ght[time,level]
    HGHT = pylab.contour(x, y, gheight, heights, colors='k', linewidths=1.5)
    pylab.clabel(HGHT, inline=1, fontsize=8, fmt='%1.0f', inline_spacing=1)

    # Convert winds from m/s to kts and then draw barbs
    u_wind_kts = u_wind_ms_ua[time, level] * 1.94384449
    v_wind_kts = v_wind_ms_ua[time, level] * 1.94384449


    pylab.barbs(x_th,y_th,u_wind_kts[::thin,::thin],\
     v_wind_kts[::thin,::thin], length=5, sizes={'spacing':0.2},pivot='middle')

    title = '%s mb Temp, Height (m), Wind (kts)' % press
    prodid = '%smb_temp' % press
    units = u"\u00B0" + "C"

    drawmap(TEMP, title, prodid, units)
def plot_ua_temps(press):
	print("    %smb TEMPERATURE" % press)
	level = levid[str(press)]
	#Set Figure Size (1000 x 800)
	pylab.figure(figsize=(width,height),frameon=False)
	heights=hght_clevs[contlevid[str(press)]]


	# Temperature calculation here
	
	#TC = temps_ua[time,level] - 273
	TH_K = np.add(temps_ua[time,level],temps_base_ua)
	TK = np.multiply(TH_K,math.pow((float(press)/1000.),(287.04/1004.))) 
	TC = TK - 273
	TEMP=pylab.contourf(x,y,TC,temp_clevs[contlevid[str(press)]],extend='both')

	# Contour the heights

	phtotal = np.add(phb[time,level],ph[time,level])
	gheight = np.divide(phtotal, 9.81)
	#gheight = ght[time,level]
	HGHT=pylab.contour(x,y,gheight,heights,colors='k',linewidths=1.5)
	pylab.clabel(HGHT,inline=1,fontsize=8,fmt='%1.0f',inline_spacing=1)


	# Convert winds from m/s to kts and then draw barbs	
	u_wind_kts = u_wind_ms_ua[time,level] * 1.94384449
	v_wind_kts = v_wind_ms_ua[time,level] * 1.94384449
	

	pylab.barbs(x_th,y_th,u_wind_kts[::thin,::thin],\
		v_wind_kts[::thin,::thin], length=5, sizes={'spacing':0.2},pivot='middle')


	title = '%s mb Temp, Height (m), Wind (kts)' % press
	prodid = '%smb_temp' % press
	units = u"\u00B0" + "C"

	drawmap(TEMP, title, prodid, units)
Beispiel #17
0
def plot_surface():
	print("    SURFACE")
	# Set Figure Size (1000 x 800)
	pylab.figure(figsize=(width,height),frameon=False)


	# Convert Surface Pressure to Mean Sea Level Pressure	
	stemps = temps[time]+6.5*nc.variables['HGT'][time]/1000.
	mslp = nc.variables['PSFC'][time]*np.exp(9.81/(287.0*stemps)*nc.variables['HGT'][time])*0.01 + (6.7 * nc.variables['HGT'][time] / 1000)

	# Convert Celsius Temps to Fahrenheit
	ftemps = (9./5.)*(temps[time]-273) + 32


	T_LEVS = range(-10,125,5)

	# Contour and fill the temperature
	T=pylab.contourf(x,y,ftemps,T_LEVS,cmap=coltbls.sftemp())

	# Contour the pressure
	P=pylab.contour(x,y,mslp,V=2,colors='k',linewidths=1.5)
	pylab.clabel(P,inline=1,fontsize=8,fmt='%1.0f',inline_spacing=1)

	#pylab.clabel(T,inline=1,fontsize=10)

	# Convert winds from m/s to kts and then draw barbs	
	u_wind_kts = u_wind_ms[time] * 1.94384449
	v_wind_kts = v_wind_ms[time] * 1.94384449
	pylab.barbs(x_th,y_th,u_wind_kts[::thin,::thin],\
		v_wind_kts[::thin,::thin], length=5,\
		sizes={'spacing':0.2},pivot='middle')

	title = 'Sfc Temp, MSLP (mb), 10m Wind (kts)'
	prodid = 'pmsl'
	units = u"\u00B0" + "F"	

	drawmap(T, title, prodid, units)
Beispiel #18
0
def skewtlogp(olga, si):
    """ 
    Get directory of script for saving arrays
    """
    tmpPath = os.path.dirname(os.path.realpath(__file__))+'/tmp/'
    if(not os.path.isdir(tmpPath)):
        os.mkdir(tmpPath)

    """
    Settings for high and low sounding top
    """
    if(si.stype==0):
        pbottom = 105000.       # highest pressure in diagram (bottom)
        ptop = 20000.           # lowest pressue in diagram (top)
        ptop_thd = 40000        # top of dry adiabats
        ptop_mxr = 60000        # top of mixing ratio lines
        pbottom_thw = pbottom   # bottom of moist adiabats
        dp = 100.               # pressure interval used in some calculations
        Tleft = -35.            # lowest temperature (@pb) in diagram (left)
        Tright = 35.            # highest temperature (@pb) in diagram (right)
        dp_label = 7000

        isotherms     = np.arange(-100,30.001,10)
        isobars       = np.array([1050.,1000.,850.,700.,500.,400.,300.,250.,200.,150.,100.,50])*100.
        dryadiabats   = np.arange(-30,50.001,10) 
        moistadiabats = np.array([28.,24.,20.,16.,12.,8.,4.,0.])
        mixrat        = np.array([20.,12.,8.,5.,3.,2.,1.])
    elif(si.stype==1):
        pbottom = 105000.       # highest pressure in diagram (bottom)
        ptop = 50000.           # lowest pressue in diagram (top)
        ptop_thd = 70000        # top of dry adiabats
        ptop_mxr = 70000        # top of mixing ratio lines
        pbottom_thw = pbottom   # bottom of moist adiabats
        dp = 100.               # pressure interval used in some calculations
        Tleft = -11.            # lowest temperature (@pb) in diagram (left)
        Tright = 35.            # highest temperature (@pb) in diagram (right)
        dp_label = 2500         # spacing (in pressure coords) of some label placement

        isotherms     = np.arange(-100,60.001,10)
        isobars       = np.array([1050.,1000.,900.,850.,700.,600.,500.])*100.
        dryadiabats   = np.arange(-10,30.001,5) 
        moistadiabats = np.array([28.,24.,20.,16.,12.,8.,4.,0.])
        mixrat        = np.array([20.,12.,8.,5.,3.,2.,1.])
    else:
        sys.exit('stype=%i not supported!'%stype)

    """
    Setup figure
    """
    if(olga != -1):
        fig = pl.figure(figsize=(olga.fig_width_px/float(olga.fig_dpi), olga.fig_width_px/float(olga.fig_dpi)))
    else:
        fig = pl.figure(figsize=(8,8))

    #                   L    B    R    T    ws  hs
    fig.subplots_adjust(0.08,0.10,1.0,0.93,0.2,0.08)
    pl.subplot(111)

    # Calculate bounds in figure coordinates
    y00 = skewty(pbottom)
    y11 = skewty(ptop)
    x00 = skewtx(Tleft,y00)
    x11 = skewtx(Tright,y00)

    # Spacing for some labels
    hs = np.abs(x11-x00)/200.
    vs = np.abs(y11-y00)/200.
 
    """
    1. Create isotherms
    """
    for T in isotherms:
        y = np.array([skewty(pbottom),skewty(ptop)])
        x = np.array([skewtx(T,y[0]),skewtx(T,y[1])])

        # Check if partially out of bounds
        lloc = 0
        if(x[0] < x00):
            x[0] = x00
            y[0] = iskewtxT(x00,T)
        if(x[1] > x11):
            x[1] = x11
            y[1] = iskewtxT(x11,T)

        if(x[1] >= x00 and y[1] >= y00):
            pl.plot(x,y,color=c2,alpha=a1)
            if(x[0] > x00 and x[0] < x11):
              pl.text(x[0],y[0]-2*hs,int(T),ha='center',va='top',color=c2)
            else:
              pl.text(x[1]-5*hs,y[1]-5*vs,int(T),ha='center',va='center',color=c2,alpha=a2)

    """
    2. Create isobars
    """
    for p in isobars:
        # Check if out of bounds
        if((p >= ptop) and (p <= pbottom)):
            y = skewty(p)
            pl.plot([x00,x11],[y,y],color=c2,alpha=a1)
            pl.text(x00-hs,y,int(p/100.),ha='right',va='center',color=c2)
         
    """
    3. Create dry adiabats
    """
    # Try loading the data from the tmp directory. If not available, calculate
    # and save the arrays
    try:
        p = np.load(tmpPath+'theta_p_%i.arr'%si.stype)
        y = np.load(tmpPath+'theta_y_%i.arr'%si.stype)
        x = np.load(tmpPath+'theta_x_%i.arr'%si.stype)
    except:
        p = np.arange(pbottom,(np.max(([ptop,ptop_thd]))-dp),-dp)
        x = np.zeros((dryadiabats.size, p.size))   
        y = np.zeros(p.size)   

        for k in range(p.size):
            y[k] = skewty(p[k])
        for i in range(dryadiabats.size):
            x[i,:] = 0.
            for k in range(p.size):
                xtmp = skewtx(((dryadiabats[i]+T0) * exner(p[k]))-T0, y[k])
                if(xtmp >= x00 and xtmp <= x11):
                    x[i,k] = xtmp
                else:
                    x[i,k] = -9999

        p.dump(tmpPath+'theta_p_%i.arr'%si.stype)
        y.dump(tmpPath+'theta_y_%i.arr'%si.stype)
        x.dump(tmpPath+'theta_x_%i.arr'%si.stype)

    # Plot the dry adiabats
    for i in range(dryadiabats.size): 
        doPlot = np.where(x[i,:] != -9999)[0]
        if(doPlot[0].size > 0):
            lloc = max(0,np.size(x[i,doPlot])-int(5000./dp))
            pl.plot(x[i,doPlot],y[doPlot],color=c1)
            pl.text(x[i,doPlot][lloc],y[doPlot][lloc],int(dryadiabats[i]),color=c1,ha='center',va='center',backgroundcolor='w')

    """ 
    4. Create moist adiabats
    """
    # Try loading the data from the tmp directory. If not available, calculate
    # and save the arrays
    try:
        p = np.load(tmpPath+'thetam_p_%i.arr'%si.stype)
        y = np.load(tmpPath+'thetam_y_%i.arr'%si.stype)
        x = np.load(tmpPath+'thetam_x_%i.arr'%si.stype)
    except:
        p = np.arange(np.min(([pbottom,pbottom_thw])),ptop-dp,-dp)
        x = np.zeros((moistadiabats.size, p.size))
        y = np.zeros(p.size)

        for k in range(p.size):
            y[k] = skewty(p[k])
        for i in range(moistadiabats.size):
            for k in range(p.size):
                thw = dsatlftskewt(moistadiabats[i], p[k])
                xtmp = skewtx(thw, y[k])
                if(xtmp >= x00 and xtmp <= x11):
                    x[i,k] = xtmp
                else:
                    x[i,k] = -9999
        
        p.dump(tmpPath+'thetam_p_%i.arr'%si.stype)
        y.dump(tmpPath+'thetam_y_%i.arr'%si.stype)
        x.dump(tmpPath+'thetam_x_%i.arr'%si.stype)
    
    # Plot the moist adiabats
    for i in range(moistadiabats.size):
        doPlot = np.where(x[i,:] != -9999)[0]
        if(doPlot[0].size > 0):
            lloc = max(0,np.size(x[i,doPlot])-int(8000./dp))
            pl.plot(x[i,doPlot],y[doPlot],'--',color=c3)
            pl.text(x[i,doPlot][lloc],y[doPlot][lloc],int(moistadiabats[i]),color=c3,ha='center',va='center',backgroundcolor='w')
 
    """ 
    5. Create isohumes / mixing ratio lines
    """
    # Try loading the data from the tmp directory. If not available, calculate
    # and save the arrays
    try:
        p = np.load(tmpPath+'mixr_p_%i.arr'%si.stype)
        y = np.load(tmpPath+'mixr_y_%i.arr'%si.stype)
        x = np.load(tmpPath+'mixr_x_%i.arr'%si.stype)
    except:
        p = np.arange(pbottom,(np.max(([ptop,ptop_mxr]))-dp),-dp)
        x = np.zeros((mixrat.size, p.size))
        y = np.zeros(p.size)

        for k in range(p.size):
            y[k] = skewty(p[k])
        for i in range(mixrat.size):
            for k in range(p.size):
                mix = Td(mixrat[i]/1000.,p[k])-T0 
                xtmp = skewtx(mix,y[k])
                if(xtmp >= x00 and xtmp <= x11):
                    x[i,k] = xtmp
                else:
                    x[i,k] = -9999

        p.dump(tmpPath+'mixr_p_%i.arr'%si.stype)
        y.dump(tmpPath+'mixr_y_%i.arr'%si.stype)
        x.dump(tmpPath+'mixr_x_%i.arr'%si.stype)

    # Plot the mixing ratio lines
    for i in range(mixrat.size):
        doPlot = np.where(x[i,:] != -9999)[0]
        if(doPlot[0].size > 0):
            pl.plot(x[i,doPlot],y[doPlot],color=c5,dashes=[3,2])
            pl.text(x[i,doPlot][-1],y[doPlot][-1]+vs,int(mixrat[i]),color=c5,ha='center',va='bottom',backgroundcolor='w')

    """
    6. Add sounding data
    """
    # 6.1 Temperature and dewpoint temperature
    if(si.T.size > 0):
        y = skewty(si.p)
        x1 = skewtx(si.T-T0,y)
        x2 = skewtx(si.Td-T0,y)

        pl.plot(x1,y,'-',color=cT,linewidth=2)
        pl.plot(x2,y,'-',color=cTd,linewidth=2)

    # 6.2 Add height labels to axis
    if(si.z.size > 0 and si.z.size==si.p.size):
        y = skewty(si.p)
        p_last = 1e9 
        for k in range(si.z.size):
            if(y[k] <= y11 and np.abs(si.p[k]-p_last) > dp_label):
                pl.text(x11+hs,y[k],str(int(si.z[k]))+'m',color=c2,ha='right',va='center',size=7,backgroundcolor='w')
                p_last = si.p[k]

    # 6.2 Wind barbs
    if(si.u.size > 0):
        y   = skewty(si.p)
        u   = si.u * 1.95
        v   = si.v * 1.95 
        xb  = x11 + 9*hs 

        p_last = 1e9 
        for k in range(si.z.size):
            if(y[k] <= y11 and np.abs(si.p[k]-p_last) > dp_label):
                pl.barbs(xb,y[k],u[k],v[k],length=5.2,linewidth=0.5,pivot='middle')  
                p_last = si.p[k]

    """
    6.1 :) Try to add measured data
    """
    # 6.1 Temperature and dewpoint temperature
    if(si.Tm.size > 0):
        y  = skewty(si.pm)
        x1 = skewtx(si.Tm,y)
        x2 = skewtx(si.Tdm,y)

        pl.plot(x1,y,'--',color=cT,linewidth=1)
        pl.plot(x2,y,'--',color=cTd,linewidth=1)

    """
    7. Lauch parcel
    """
    if(si.parcel == True):
        # Plot starting position:
        p0s  = skewty(si.ps)
        T0s  = skewtx(si.Ts-T0, p0s)
        Td0s = skewtx(Td(si.rs,si.ps)-T0, p0s)
        pl.scatter(T0s, p0s, facecolor='none')
        pl.scatter(Td0s,p0s, facecolor='none')

        # Lists to hold parcel pressure, temp and dewpoint temp during ascent
        pp  = [si.ps]
        Tp  = [si.Ts]
        Tdp = [Td(si.rs, si.ps)]

        # Launch parcel
        n = 0
        while(Tp[-1] > Tdp[-1] and n<1000):
            n  += 1
            dp2 = max(1,(Tp[-1] - Tdp[-1])*300) # bit weird, but fast
            pp. append(pp[-1] - dp2)
            Tp. append(si.Ts*exner(pp[-1], si.ps))
            Tdp.append(Td(si.rs, pp[-1]))

        # Plot lines from surface --> LCL
        ps   = skewty(np.array(pp))
        Tps  = skewtx(np.array(Tp)-T0,  ps)
        Tdps = skewtx(np.array(Tdp)-T0, ps)
        pl.plot(Tps,  ps, 'k', linewidth=1.5, dashes=[4,2])
        pl.plot(Tdps, ps, 'k', linewidth=1.5, dashes=[4,2])
        pl.scatter(Tps[-1], ps[-1], facecolor='none')

        # Iteratively find the moist adiabat starting at p0, which goes through the temperature at LCL
        Ths      = si.Ts / exner(si.ps, p0)         # potential temperature surface (@p0)
        ThwsLCL  = dsatlftskewt(Ths-T0, pp[-1])+T0  # Temp moist adiabat at plcl, through Ths
        thw0     = Ths - (ThwsLCL - Tp[-1])         # First estimate of moist adiabat passing through Tlcl

        ThwLCL   = dsatlftskewt(thw0-T0, pp[-1])+T0
        while(np.abs(ThwLCL-Tp[-1]) > 0.1):
            thw0    -= ThwLCL-Tp[-1] 
            ThwLCL   = dsatlftskewt(thw0-T0, pp[-1])+T0

        # Plot moist adiabat from LCL upwards
        p = np.arange(pp[-1], ptop, -dp)
        x = np.zeros(p.size)
        y = np.zeros(p.size)
        for k in range(p.size):
            thw = dsatlftskewt(thw0-T0,p[k])
            y[k] = skewty(p[k])
            x[k] = skewtx(thw,y[k])

        pl.plot(x,y,'k', linewidth=1.5, dashes=[4,2])


    """
    Add info from TEMF boundary layer scheme
    """
    if(si.Tu.size > 0):
        # Cloud fraction
        dw = (x11-x00)    # width of diagram
        y  = skewty(si.p)
        x = x00 + si.cfru * 0.2 * (x11-x00)
        pl.plot(x,y,'-',linewidth=1.5,color=c6) # cloud cover

        cfr_pos = np.where(si.cfru > 0.001)[0]
        if(np.size(cfr_pos)>1):
            pl.text(x00,y[cfr_pos[0]-1],'- %im'%(si.z[cfr_pos[0]-1]),ha='left',va='center',size=8,color=c6)
            pl.text(x00,y[cfr_pos[-1]],'- %im'%(si.z[cfr_pos[-1]]),ha='left',va='center',size=8,color=c6)
            kmax=np.where(si.cfru == si.cfru.max())[0][0]
            pl.text(x.max(),y[kmax],'- %i%%'%(si.cfru[kmax]*100.),ha='left',va='center',size=8,color=c6)

    """
    6. Finish diagram
    """ 
    pl.xticks([])
    pl.yticks([])
    pl.box('off')
    pl.xlim(x00-0.1,x11+16*hs)
    pl.ylim(y00-0.1,y11+0.1)

    # draw axis
    pl.plot([x00,x11],[y00,y00],'k-')
    pl.plot([x00,x00],[y00,y11],'k-')

    pl.figtext(0.5,0.05,'Temperature (C)',ha='center')
    pl.figtext(0.015,0.52,'Pressure (hPa)',rotation=90)
    label = 'Skew-T log-P, %s, %s UTC'%(si.name,si.time) 
    pl.figtext(0.5,0.97,label,ha='center')

    if(olga != -1):
        img = image.imread(olga.olgaRoot+'include/olga_left.png')
        pl.figimage(img,7,5)
        #pl.figimage(img,10,olga.fig_width_px-45)
        pl.figtext(0.99,0.011,'%s'%olga.map_desc[0],size=7,ha='right')

    return fig
def main():
    base_time = datetime(2009, 6, 5, 18, 0, 0)
    epoch = datetime(1970, 1, 1, 0, 0, 0)
    base_epoch = (base_time - epoch).total_seconds()
    times_seconds = range(14700, 18300, 300)
    times = [ base_time + timedelta(seconds=t) for t in times_seconds ]

    bounds = (slice(100, 180), slice(90, 170))
    rev_bounds = [ 0 ]
    rev_bounds.extend(bounds[::-1])
    rev_bounds = tuple(rev_bounds)

    proj = setupMapProjection(goshen_1km_proj, goshen_1km_gs, bounds=bounds)
    map = Basemap(**proj)

    obs_file_names = ['psu_straka_mesonet.pkl', 'ttu_sticknet.pkl', 'asos.pkl', 'soundings_clip.pkl']
    all_obs = loadObs(obs_file_names, times, map, (goshen_1km_proj['width'], goshen_1km_proj['height']), sounding_obs=['soundings_clip.pkl'])

    refl_base = "hdf/KCYS/1km/goshen.hdfrefl2d"
    refl_times = np.array([ int(f[-6:]) for f in glob.glob("%s??????" % refl_base) ])
    refl_keep_times = []
    refl_data = {}

    for tt in times_seconds:
        idx = np.argmin(np.abs(refl_times - tt))
        if refl_times[idx] > tt and idx > 0:
            idx -= 1

        file_name = "%s%06d" % (refl_base, refl_times[idx])
        hdf = nio.open_file(file_name, mode='r', format='hdf')
        refl_keep_times.append(refl_times[idx])
        refl_data[tt] = hdf.variables['refl2d'][rev_bounds]

    for time, reg in inflow_stations.iteritems():
        pylab.figure()

        gs_x, gs_y = goshen_1km_gs
        nx, ny = refl_data[time].shape
        xs, ys = np.meshgrid(gs_x * np.arange(nx), gs_y * np.arange(ny))
        pylab.contourf(xs, ys, refl_data[time], levels=np.arange(10, 80, 10))

        for region, stations in reg.iteritems():
            if region != 'sounding':
                for station in stations:
                    idxs = np.where((all_obs['id'] == station) & (all_obs['time'] == base_epoch + time))
                    ob_xs, ob_ys = map(all_obs['longitude'][idxs], all_obs['latitude'][idxs])

                    if region == 'inflow': color='r'
                    elif region == 'outflow': color='b'

                    wdir = all_obs['wind_dir'][idxs]
                    wspd = all_obs['wind_spd'][idxs]
                    u = -wspd * np.sin(wdir * np.pi / 180.) * 1.94
                    v = -wspd * np.cos(wdir * np.pi / 180.) * 1.94

                    pylab.plot(ob_xs, ob_ys, "%so" % color)
                    pylab.barbs(ob_xs, ob_ys, u, v)

        drawPolitical(map, scale_len=10)

        pylab.savefig("inflow_stations_%06d.png" % time)
        pylab.close()

    return
def main():
    base_time = datetime(2009, 6, 5, 18, 0, 0)
    epoch = datetime(1970, 1, 1, 0, 0, 0)
    base_epoch = (base_time - epoch).total_seconds()
    times_seconds = range(14700, 18300, 300)
    times = [base_time + timedelta(seconds=t) for t in times_seconds]

    bounds = (slice(100, 180), slice(90, 170))
    rev_bounds = [0]
    rev_bounds.extend(bounds[::-1])
    rev_bounds = tuple(rev_bounds)

    proj = setupMapProjection(goshen_1km_proj, goshen_1km_gs, bounds=bounds)
    map = Basemap(**proj)

    obs_file_names = [
        'psu_straka_mesonet.pkl', 'ttu_sticknet.pkl', 'asos.pkl',
        'soundings_clip.pkl'
    ]
    all_obs = loadObs(obs_file_names,
                      times,
                      map,
                      (goshen_1km_proj['width'], goshen_1km_proj['height']),
                      sounding_obs=['soundings_clip.pkl'])

    refl_base = "hdf/KCYS/1km/goshen.hdfrefl2d"
    refl_times = np.array(
        [int(f[-6:]) for f in glob.glob("%s??????" % refl_base)])
    refl_keep_times = []
    refl_data = {}

    for tt in times_seconds:
        idx = np.argmin(np.abs(refl_times - tt))
        if refl_times[idx] > tt and idx > 0:
            idx -= 1

        file_name = "%s%06d" % (refl_base, refl_times[idx])
        hdf = nio.open_file(file_name, mode='r', format='hdf')
        refl_keep_times.append(refl_times[idx])
        refl_data[tt] = hdf.variables['refl2d'][rev_bounds]

    for time, reg in inflow_stations.iteritems():
        pylab.figure()

        gs_x, gs_y = goshen_1km_gs
        nx, ny = refl_data[time].shape
        xs, ys = np.meshgrid(gs_x * np.arange(nx), gs_y * np.arange(ny))
        pylab.contourf(xs, ys, refl_data[time], levels=np.arange(10, 80, 10))

        for region, stations in reg.iteritems():
            if region != 'sounding':
                for station in stations:
                    idxs = np.where((all_obs['id'] == station)
                                    & (all_obs['time'] == base_epoch + time))
                    ob_xs, ob_ys = map(all_obs['longitude'][idxs],
                                       all_obs['latitude'][idxs])

                    if region == 'inflow': color = 'r'
                    elif region == 'outflow': color = 'b'

                    wdir = all_obs['wind_dir'][idxs]
                    wspd = all_obs['wind_spd'][idxs]
                    u = -wspd * np.sin(wdir * np.pi / 180.) * 1.94
                    v = -wspd * np.cos(wdir * np.pi / 180.) * 1.94

                    pylab.plot(ob_xs, ob_ys, "%so" % color)
                    pylab.barbs(ob_xs, ob_ys, u, v)

        drawPolitical(map, scale_len=10)

        pylab.savefig("inflow_stations_%06d.png" % time)
        pylab.close()

    return
Beispiel #21
0
		pylab.semilogy(temp_trans,actual_press_levels, \
			color = 'red',basey=10, linewidth = 2)
	



		#print Tp, press_p
		#raw_input()
		#pylab.semilogy(Tp_trans,press_p,color = 'brown',\
		#	basey = 10, linewidth = 2, linestyle = 'dashed')
		baraxis = []
		# Need this -3 to the list to stop them from going off the top
		for n in range(len(u_wind_kts[:-5])):
			baraxis.append(45.)
		pylab.plot([45,45],[100,1000],linewidth = .75, color = 'k')
		bb = pylab.barbs(baraxis,actual_wind_levs[:-5],u_wind_kts[:-5],v_wind_kts[:-5],\
			linewidth = .75)
		bb.set_clip_box(None)
		ax = pylab.gca()
		#ax.set_ylim(ax.get_ylim()[::-1])
		ax.set_ylim([1000,100])
		ax.set_xlim([-40,50])
		majorLocator = MultipleLocator(100.)
		majorFormatter = FormatStrFormatter('%4.0f')
		ax.yaxis.set_major_locator(majorLocator)
		ax.yaxis.set_major_formatter(majorFormatter)

		stemps = sfcT[time,point_y,point_x]+6.5*ncsfc.variables['HGT'][time,point_y,point_x]/1000.
		mslp = sfcP[time,point_y,point_x]*np.exp(9.81/(287.0*stemps)*ncsfc.variables['HGT'][time,point_y,point_x])*0.01 + (6.7 * ncsfc.variables['HGT'][time,point_y,point_x] / 1000)

		# Convert Celsius Temps to Fahrenheit
		ftemp = (9./5.)*(sfcT[time,point_y,point_x]-273) + 32
Beispiel #22
0
def create_timeseries(olga, wrfout, dom, times):

    # colormap for cloud cover
    cld = make_colormap({0.: '#05b5ff', 0.3: '#bdecff', 1.0: '#ffffff'})

    olga_logo = pl.matplotlib.image.imread(olga.olgaRoot +
                                           'include/olga_left.png')

    # Loop over requested locations
    for name, longName, lon, lat, type in zip(olga.soundLoc[dom].shortName,
                                              olga.soundLoc[dom].longName,
                                              olga.soundLoc[dom].lon,
                                              olga.soundLoc[dom].lat,
                                              olga.soundLoc[dom].type):
        if (type == 0 or type == 2):
            # Read WRF data
            d = readwrf_loc(olga, wrfout, lon, lat, times[0], times[-1])

            # DEBUGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGG
            #figure()
            #for t in range(np.size(d.t0_ana)):
            #    t0 = d.t0_ana[t]
            #    t1 = d.t1_ana[t]
            #    figure()
            #    for tt in range(t0,t1):
            #        sp = tt-t0
            #        ax=subplot(5,4,sp+1)
            #        title(str(tt))
            #        d.w[tt,d.w[tt,:]<0] = 0
            #        plot(d.w[tt,:], d.zf[tt,:],'r-',label='w_up')
            #        plot(d.qltemf[tt,:]*10000, d.zf[tt,:],'b-',label='ql_up*1e4')
            #        ylim(0,3000)
            #        xlim(0,3)
            #        if(tt == t0): legend(frameon=False)
            #        if(sp % 4 != 0): ax.tick_params(labelleft='off')
            #        if(sp < 16): ax.tick_params(labelbottom='off')
            #        grid()

            #    savefig('test_%s.png'%name)

            # Loop over diffent day (if available):
            for t in range(np.size(d.t0_ana)):
                t0 = d.t0_ana[t]
                t1 = d.t1_ana[t]
                x0 = d.hour[t0]
                x1 = d.hour[t1]

                fig = pl.figure(
                    figsize=(olga.fig_width_px / float(olga.fig_dpi),
                             olga.fig_width_px / float(olga.fig_dpi)))
                #                   L    B    R    T    ws  hs
                fig.subplots_adjust(0.10, 0.11, 0.98, 0.88, 0.35, 0.55)
                pl.figtext(0.5,
                           0.95,
                           '%s [%.2fN, %.2fE]' % (longName, lat, lon),
                           size=9,
                           ha='center')
                pl.figtext(0.5, 0.93, '%s' % (d.date[t0]), size=8, ha='center')
                gs = pl.matplotlib.gridspec.GridSpec(
                    4, 2, height_ratios=[1., 1., 0.4, 1], width_ratios=[2, 1])

                # -------------------------------------------------
                # Updraft velocity / height: wstar
                # -------------------------------------------------
                #ax = pl.subplot(gs[:2,0]); modplot(ax)
                #ax.set_title('Updraft velocity and height',loc='left')
                #zs = d.z[0,0]  # terrain height (lowest half level)
                #wm = 3.5       # scaling for colormap
                #bw1 = 0.6      # width of sub-cloud updrafts
                #bw2 = 0.8      # width of cloud updrafts
                #for i in range(t0,t1+1):
                #    if(d.wglider[i] > 0.0):
                #        color = wup((np.floor(d.wglider[i])+0.5)/wm)
                #        pl.bar(d.hour[i]-0.5*bw1, d.zi[i],         width=bw1, bottom=zs,         color=color,           edgecolor='none')
                #        pl.bar(d.hour[i]-0.5*bw2, d.ct[i]-d.zi[i], width=bw2, bottom=d.zi[i]+zs, color='k',  alpha=0.3, edgecolor='none')

                ## Add surface
                #pl.plot([d.hour[t0], d.hour[t1]],[zs, zs], 'k:')
                #pl.text(d.hour[t0]+0.2,zs,'surface',size=7,ha='left',va='bottom')

                ## Add sort-of colorbar
                #wups = ([0.5,1.5,2.5,3.5])
                #names = (['0-1 m/s','1-2 m/s','2-3 m/s','>3 m/s'])
                #for wu,nam in zip(wups,names):
                #    pl.scatter([-10],[300],color=wup(wu/wm),label=nam)
                #pl.legend(frameon=False,loc=2)
                #pl.xlim(d.hour[t0],d.hour[t1])
                #pl.ylim(0,3000)
                #pl.ylabel('z [m AMSL]')
                #pl.xticks(np.arange(d.hour[t0],d.hour[t1]+0.001,2))
                #pl.yticks(np.arange(0,3000.001,500))

                # -------------------------------------------------
                # Updraft velocity / height: vertical velocity TEMF
                # -------------------------------------------------
                ax = pl.subplot(gs[:2, 0])
                modplot(ax)
                ax.set_title('Updraft velocity and height', loc='left', size=8)
                zs = d.z[0, 0]  # terrain height (lowest half level)
                wm = 4  # scaling for colormap
                bw1 = 0.70  # width of sub-cloud updrafts
                bw2 = 0.85  # width of cloud updrafts

                # Loop over all time steps
                for tt in range(d.nt):
                    # TO-DO: TEMF often doesn't decay updraft velocity after convection stop.
                    # Limit plot to conditions with unstable near-surface layer:
                    if (d.thv[tt, 1] < d.thv[tt, 0]):
                        # Plot updraft velocity
                        wc_p, cc_p = w_discretized(d.w[tt, 0])
                        k_p = 0
                        wc_max = 0
                        for k in range(key_nearest(d.zf[tt, :], 3000) + 1):
                            # Current discretized updraft velocity
                            wc_a, cc_a = w_discretized(d.w[tt, k])
                            wc_max = np.max((wc_max, wc_a))

                            # If current velocity differs from previous, draw bar from k_p to k
                            if (wc_a != wc_p):
                                pl.bar(d.hour[tt] - 0.5 * bw1,
                                       d.z[tt, k] - d.z[tt, k_p],
                                       width=bw1,
                                       bottom=d.z[tt, k_p],
                                       color=cc_p,
                                       edgecolor='none')
                                wc_p = wc_a
                                cc_p = cc_a
                                k_p = k

                        # Plot cumulus clouds, only if there is something like an updraft below
                        if (wc_max > 0):
                            cloud = False  # flag to see if we have cumulus
                            for k in range(key_nearest(d.zf[tt, :], 3000) + 1):
                                ql = np.max((0, d.qltemf[tt, k]))

                                if (ql >= 5e-5 and cloud == False):
                                    cloud = True
                                    kc_p = k

                                if (ql < 5e-5 and cloud == True):
                                    pl.bar(d.hour[tt] - 0.5 * bw2,
                                           d.z[tt, k + 1] - d.z[tt, kc_p],
                                           width=bw2,
                                           bottom=d.z[tt, kc_p],
                                           color='0.9',
                                           edgecolor='k',
                                           alpha=0.5)
                                    cloud = False

                # Add line at surface
                pl.plot([d.hour[t0], d.hour[t1]], [zs, zs], 'k:')
                pl.text(d.hour[t0] + 0.2,
                        zs,
                        'surface',
                        size=7,
                        ha='left',
                        va='bottom')

                # Add sort-of colorbar
                wups = ([0.7, 1, 2, 3])
                names = (['0.7-1 m/s', '1-2 m/s', '2-3 m/s', '>3 m/s'])
                for wu, nam in zip(wups, names):
                    tmp, cc = w_discretized(wu)
                    pl.scatter([-10], [300], marker='s', color=cc, label=nam)
                pl.plot([-10, -10], [300, 300], 'k-', label='cumulus')
                pl.legend(frameon=False, loc=2, scatterpoints=1)
                pl.xlim(d.hour[t0], d.hour[t1])
                pl.ylim(0, 3000)
                pl.ylabel('z [m AMSL]')
                pl.xticks(np.arange(d.hour[t0], d.hour[t1] + 0.001, 2))
                pl.yticks(np.arange(0, 3000.001, 500))

                # -------------------------------------------------
                # Pressure
                # -------------------------------------------------
                ax = pl.subplot(gs[0, 1])
                modplot(ax)
                ax.set_title('Surface pressure', loc='left', size=8)
                slp = d.slps[t0:t1] / 100.
                pl.plot(d.hour[t0:t1], slp, 'k-')
                pl.xlim(d.hour[t0], d.hour[t1])
                pl.ylabel('hPa')
                pl.xticks(np.arange(d.hour[t0], d.hour[t1] + 0.001, 2))
                if (slp.max() - slp.min() < 10):
                    pl.ylim(
                        roundNumber(slp.mean(), 1, DOWN) - 5,
                        roundNumber(slp.mean(), 1, UP) + 5)

                # -------------------------------------------------
                # Air temperature / dew poiunt temperature
                # -------------------------------------------------
                ax = pl.subplot(gs[1, 1])
                modplot(ax)
                ax.set_title('T and Td at 2m', loc='left', size=8)
                pl.plot(d.hour[t0:t1], d.T2[t0:t1] - 273.15, 'k-', label='T')
                pl.plot(d.hour[t0:t1],
                        d.Td2[t0:t1] - 273.15,
                        'k-',
                        label='Td',
                        dashes=[4, 2])
                pl.ylabel('celcius')
                pl.xlim(d.hour[t0], d.hour[t1])
                pl.xticks(np.arange(d.hour[t0], d.hour[t1] + 0.001, 2))
                pl.legend(frameon=False, loc=2)

                # -------------------------------------------------
                # Rain
                # -------------------------------------------------
                ax = pl.subplot(gs[2, 1])
                modplot(ax)
                ax.set_title('Rain', loc='left', size=8)
                pl.bar(d.hour[t0:t1],
                       d.drr_mp[t0:t1],
                       color='g',
                       edgecolor='none')
                pl.bar(d.hour[t0:t1],
                       d.drr_con[t0:t1],
                       bottom=d.drr_mp[t0:t1],
                       color='b',
                       edgecolor='none')
                pl.ylabel('mm')
                pl.xlim(d.hour[t0], d.hour[t1])
                pl.xticks(np.arange(d.hour[t0], d.hour[t1] + 0.001, 2))
                pl.ylim(
                    0,
                    max(
                        1,
                        roundNumber((d.drr_mp[t0:t1] + d.drr_con[t0:t1]).max(),
                                    1, UP)))

                # -------------------------------------------------
                # Shortwave radiation
                # -------------------------------------------------
                ax = pl.subplot(gs[3, 1])
                modplot(ax)
                ax.set_title('Shortwave radiation', loc='left', size=8)
                pl.plot(d.hour[t0:t1], d.swd[t0:t1], 'k-')
                pl.plot(d.hour[t0:t1],
                        d.swdc[t0:t1],
                        'k-',
                        label='Pot.',
                        dashes=[4, 2])
                pl.ylabel('W/m2')
                pl.xlabel('time UTC [h]')
                pl.xlim(d.hour[t0], d.hour[t1])
                pl.xticks(np.arange(d.hour[t0], d.hour[t1] + 0.001, 2))
                pl.ylim(0, 1000)
                pl.yticks(np.arange(0, 1000.01, 200))
                pl.legend(frameon=False, loc=2, borderpad=0)

                # -------------------------------------------------
                # Cloud cover
                # -------------------------------------------------
                ax = pl.subplot(gs[2, 0])
                modplot(ax)
                ax.set_title('Cloud cover', loc='left', size=8)
                pl.pcolormesh(d.ccl, cmap=cld, vmin=0, vmax=1)
                pl.text(d.hour[t0] - 0.4,
                        0.5,
                        'low',
                        size=7,
                        ha='right',
                        va='center')
                pl.text(d.hour[t0] - 0.4,
                        1.5,
                        'middle',
                        size=7,
                        ha='right',
                        va='center')
                pl.text(d.hour[t0] - 0.4,
                        2.5,
                        'high',
                        size=7,
                        ha='right',
                        va='center')
                pl.xlim(d.hour[t0], d.hour[t1])
                ax.set_yticks([])
                pl.xticks(np.arange(d.hour[t0], d.hour[t1] + 0.001, 2))

                # -------------------------------------------------
                # Wind
                # -------------------------------------------------
                ax = pl.subplot(gs[3, 0])
                modplot(ax)
                ax.set_title('Wind', loc='left', size=8)
                k500 = key_nearest(d.zf[0, :], 500)
                k1000 = key_nearest(d.zf[0, :], 1000)
                k2000 = key_nearest(d.zf[0, :], 2000)
                pl.barbs(d.hour[t0:t1 + 1],
                         0.5,
                         d.u10[t0:t1 + 1] * m2k,
                         d.v10[t0:t1 + 1] * m2k,
                         length=5,
                         linewidth=0.5,
                         pivot='middle')
                pl.barbs(d.hour[t0:t1 + 1],
                         1.5,
                         d.u[t0:t1 + 1, k500] * m2k,
                         d.v[t0:t1 + 1, k500] * m2k,
                         length=5,
                         linewidth=0.5,
                         pivot='middle')
                pl.barbs(d.hour[t0:t1 + 1],
                         2.5,
                         d.u[t0:t1 + 1, k1000] * m2k,
                         d.v[t0:t1 + 1, k1000] * m2k,
                         length=5,
                         linewidth=0.5,
                         pivot='middle')
                pl.barbs(d.hour[t0:t1 + 1],
                         3.5,
                         d.u[t0:t1 + 1, k2000] * m2k,
                         d.v[t0:t1 + 1, k2000] * m2k,
                         length=5,
                         linewidth=0.5,
                         pivot='middle')
                pl.text(d.hour[t0] - 0.4,
                        0.5,
                        '10m',
                        size=7,
                        ha='right',
                        va='center')
                pl.text(d.hour[t0] - 0.4,
                        1.5,
                        '500m',
                        size=7,
                        ha='right',
                        va='center')
                pl.text(d.hour[t0] - 0.4,
                        2.5,
                        '1000m',
                        size=7,
                        ha='right',
                        va='center')
                pl.text(d.hour[t0] - 0.4,
                        3.5,
                        '2000m',
                        size=7,
                        ha='right',
                        va='center')
                pl.xlim(0, 24)
                pl.xlim(d.hour[t0], d.hour[t1])
                ax.set_yticks([])
                pl.xticks(np.arange(d.hour[t0], d.hour[t1] + 0.001, 2))
                pl.xlabel('time UTC [h]')

                # Add logo (105px wide)
                pl.figimage(olga_logo, 10, olga.fig_width_px - 40)
                pl.figtext(0.01,
                           0.011,
                           '%s' % (olga.map_desc[dom]),
                           size=7,
                           ha='left')

                # Save figure
                tmp = '%06i' % (olga.islice * 24 * 100)
                name = '%s%04i%02i%02i_t%02iz/tser_%s_%02i_%s.png' % (
                    olga.figRoot, olga.year, olga.month, olga.day, olga.cycle,
                    name, dom + 1, tmp)
                pl.savefig(name, dpi=olga.fig_dpi)
		pylab.semilogy(temp_trans,actual_press_levels, \
			color = 'red',basey=10, linewidth = 2)
	



		#print Tp, press_p
		#raw_input()
		#pylab.semilogy(Tp_trans,press_p,color = 'brown',\
		#	basey = 10, linewidth = 2, linestyle = 'dashed')
		baraxis = []
		# Need this -3 to the list to stop them from going off the top
		for n in range(len(u_wind_kts[:-5])):
			baraxis.append(45.)
		pylab.plot([45,45],[100,1000],linewidth = .75, color = 'k')
		bb = pylab.barbs(baraxis,actual_wind_levs[:-5],u_wind_kts[:-5],v_wind_kts[:-5],\
			linewidth = .75)
		bb.set_clip_box(None)
		ax = pylab.gca()
		#ax.set_ylim(ax.get_ylim()[::-1])
		ax.set_ylim([1000,100])
		ax.set_xlim([-40,50])
		majorLocator = MultipleLocator(100.)
		majorFormatter = FormatStrFormatter('%4.0f')
		ax.yaxis.set_major_locator(majorLocator)
		ax.yaxis.set_major_formatter(majorFormatter)

		stemps = sfcT[time,point_y,point_x]+6.5*ncsfc.variables['HGT'][time,point_y,point_x]/1000.
		mslp = sfcP[time,point_y,point_x]*np.exp(9.81/(287.0*stemps)*ncsfc.variables['HGT'][time,point_y,point_x])*0.01 + (6.7 * ncsfc.variables['HGT'][time,point_y,point_x] / 1000)

		# Convert Celsius Temps to Fahrenheit
		ftemp = (9./5.)*(sfcT[time,point_y,point_x]-273) + 32
Beispiel #24
0
def skewtlogp(olga, si):
    """ 
    Get directory of script for saving arrays
    """
    tmpPath = os.path.dirname(os.path.realpath(__file__)) + '/tmp/'
    if (not os.path.isdir(tmpPath)):
        os.mkdir(tmpPath)
    """
    Settings for high and low sounding top
    """
    if (si.stype == 0):
        pbottom = 105000.  # highest pressure in diagram (bottom)
        ptop = 20000.  # lowest pressue in diagram (top)
        ptop_thd = 40000  # top of dry adiabats
        ptop_mxr = 60000  # top of mixing ratio lines
        pbottom_thw = pbottom  # bottom of moist adiabats
        dp = 100.  # pressure interval used in some calculations
        Tleft = -35.  # lowest temperature (@pb) in diagram (left)
        Tright = 35.  # highest temperature (@pb) in diagram (right)
        dp_label = 7000

        isotherms = np.arange(-100, 30.001, 10)
        isobars = np.array([
            1050., 1000., 850., 700., 500., 400., 300., 250., 200., 150., 100.,
            50
        ]) * 100.
        dryadiabats = np.arange(-30, 50.001, 10)
        moistadiabats = np.array([28., 24., 20., 16., 12., 8., 4., 0.])
        mixrat = np.array([20., 12., 8., 5., 3., 2., 1.])
    elif (si.stype == 1):
        pbottom = 105000.  # highest pressure in diagram (bottom)
        ptop = 50000.  # lowest pressue in diagram (top)
        ptop_thd = 70000  # top of dry adiabats
        ptop_mxr = 70000  # top of mixing ratio lines
        pbottom_thw = pbottom  # bottom of moist adiabats
        dp = 100.  # pressure interval used in some calculations
        Tleft = -11.  # lowest temperature (@pb) in diagram (left)
        Tright = 35.  # highest temperature (@pb) in diagram (right)
        dp_label = 2500  # spacing (in pressure coords) of some label placement

        isotherms = np.arange(-100, 60.001, 10)
        isobars = np.array([1050., 1000., 900., 850., 700., 600., 500.]) * 100.
        dryadiabats = np.arange(-10, 30.001, 5)
        moistadiabats = np.array([28., 24., 20., 16., 12., 8., 4., 0.])
        mixrat = np.array([20., 12., 8., 5., 3., 2., 1.])
    else:
        sys.exit('stype=%i not supported!' % stype)
    """
    Setup figure
    """
    if (olga != -1):
        fig = pl.figure(figsize=(olga.fig_width_px / float(olga.fig_dpi),
                                 olga.fig_width_px / float(olga.fig_dpi)))
    else:
        fig = pl.figure(figsize=(8, 8))

    #                   L    B    R    T    ws  hs
    fig.subplots_adjust(0.08, 0.10, 1.0, 0.93, 0.2, 0.08)
    pl.subplot(111)

    # Calculate bounds in figure coordinates
    y00 = skewty(pbottom)
    y11 = skewty(ptop)
    x00 = skewtx(Tleft, y00)
    x11 = skewtx(Tright, y00)

    # Spacing for some labels
    hs = np.abs(x11 - x00) / 200.
    vs = np.abs(y11 - y00) / 200.
    """
    1. Create isotherms
    """
    for T in isotherms:
        y = np.array([skewty(pbottom), skewty(ptop)])
        x = np.array([skewtx(T, y[0]), skewtx(T, y[1])])

        # Check if partially out of bounds
        lloc = 0
        if (x[0] < x00):
            x[0] = x00
            y[0] = iskewtxT(x00, T)
        if (x[1] > x11):
            x[1] = x11
            y[1] = iskewtxT(x11, T)

        if (x[1] >= x00 and y[1] >= y00):
            pl.plot(x, y, color=c2, alpha=a1)
            if (x[0] > x00 and x[0] < x11):
                pl.text(x[0],
                        y[0] - 2 * hs,
                        int(T),
                        ha='center',
                        va='top',
                        color=c2)
            else:
                pl.text(x[1] - 5 * hs,
                        y[1] - 5 * vs,
                        int(T),
                        ha='center',
                        va='center',
                        color=c2,
                        alpha=a2)
    """
    2. Create isobars
    """
    for p in isobars:
        # Check if out of bounds
        if ((p >= ptop) and (p <= pbottom)):
            y = skewty(p)
            pl.plot([x00, x11], [y, y], color=c2, alpha=a1)
            pl.text(x00 - hs,
                    y,
                    int(p / 100.),
                    ha='right',
                    va='center',
                    color=c2)
    """
    3. Create dry adiabats
    """
    # Try loading the data from the tmp directory. If not available, calculate
    # and save the arrays
    try:
        p = np.load(tmpPath + 'theta_p_%i.arr' % si.stype)
        y = np.load(tmpPath + 'theta_y_%i.arr' % si.stype)
        x = np.load(tmpPath + 'theta_x_%i.arr' % si.stype)
    except:
        p = np.arange(pbottom, (np.max(([ptop, ptop_thd])) - dp), -dp)
        x = np.zeros((dryadiabats.size, p.size))
        y = np.zeros(p.size)

        for k in range(p.size):
            y[k] = skewty(p[k])
        for i in range(dryadiabats.size):
            x[i, :] = 0.
            for k in range(p.size):
                xtmp = skewtx(((dryadiabats[i] + T0) * exner(p[k])) - T0, y[k])
                if (xtmp >= x00 and xtmp <= x11):
                    x[i, k] = xtmp
                else:
                    x[i, k] = -9999

        p.dump(tmpPath + 'theta_p_%i.arr' % si.stype)
        y.dump(tmpPath + 'theta_y_%i.arr' % si.stype)
        x.dump(tmpPath + 'theta_x_%i.arr' % si.stype)

    # Plot the dry adiabats
    for i in range(dryadiabats.size):
        doPlot = np.where(x[i, :] != -9999)[0]
        if (doPlot[0].size > 0):
            lloc = max(0, np.size(x[i, doPlot]) - int(5000. / dp))
            pl.plot(x[i, doPlot], y[doPlot], color=c1)
            pl.text(x[i, doPlot][lloc],
                    y[doPlot][lloc],
                    int(dryadiabats[i]),
                    color=c1,
                    ha='center',
                    va='center',
                    backgroundcolor='w')
    """ 
    4. Create moist adiabats
    """
    # Try loading the data from the tmp directory. If not available, calculate
    # and save the arrays
    try:
        p = np.load(tmpPath + 'thetam_p_%i.arr' % si.stype)
        y = np.load(tmpPath + 'thetam_y_%i.arr' % si.stype)
        x = np.load(tmpPath + 'thetam_x_%i.arr' % si.stype)
    except:
        p = np.arange(np.min(([pbottom, pbottom_thw])), ptop - dp, -dp)
        x = np.zeros((moistadiabats.size, p.size))
        y = np.zeros(p.size)

        for k in range(p.size):
            y[k] = skewty(p[k])
        for i in range(moistadiabats.size):
            for k in range(p.size):
                thw = dsatlftskewt(moistadiabats[i], p[k])
                xtmp = skewtx(thw, y[k])
                if (xtmp >= x00 and xtmp <= x11):
                    x[i, k] = xtmp
                else:
                    x[i, k] = -9999

        p.dump(tmpPath + 'thetam_p_%i.arr' % si.stype)
        y.dump(tmpPath + 'thetam_y_%i.arr' % si.stype)
        x.dump(tmpPath + 'thetam_x_%i.arr' % si.stype)

    # Plot the moist adiabats
    for i in range(moistadiabats.size):
        doPlot = np.where(x[i, :] != -9999)[0]
        if (doPlot[0].size > 0):
            lloc = max(0, np.size(x[i, doPlot]) - int(8000. / dp))
            pl.plot(x[i, doPlot], y[doPlot], '--', color=c3)
            pl.text(x[i, doPlot][lloc],
                    y[doPlot][lloc],
                    int(moistadiabats[i]),
                    color=c3,
                    ha='center',
                    va='center',
                    backgroundcolor='w')
    """ 
    5. Create isohumes / mixing ratio lines
    """
    # Try loading the data from the tmp directory. If not available, calculate
    # and save the arrays
    try:
        p = np.load(tmpPath + 'mixr_p_%i.arr' % si.stype)
        y = np.load(tmpPath + 'mixr_y_%i.arr' % si.stype)
        x = np.load(tmpPath + 'mixr_x_%i.arr' % si.stype)
    except:
        p = np.arange(pbottom, (np.max(([ptop, ptop_mxr])) - dp), -dp)
        x = np.zeros((mixrat.size, p.size))
        y = np.zeros(p.size)

        for k in range(p.size):
            y[k] = skewty(p[k])
        for i in range(mixrat.size):
            for k in range(p.size):
                mix = Td(mixrat[i] / 1000., p[k]) - T0
                xtmp = skewtx(mix, y[k])
                if (xtmp >= x00 and xtmp <= x11):
                    x[i, k] = xtmp
                else:
                    x[i, k] = -9999

        p.dump(tmpPath + 'mixr_p_%i.arr' % si.stype)
        y.dump(tmpPath + 'mixr_y_%i.arr' % si.stype)
        x.dump(tmpPath + 'mixr_x_%i.arr' % si.stype)

    # Plot the mixing ratio lines
    for i in range(mixrat.size):
        doPlot = np.where(x[i, :] != -9999)[0]
        if (doPlot[0].size > 0):
            pl.plot(x[i, doPlot], y[doPlot], color=c5, dashes=[3, 2])
            pl.text(x[i, doPlot][-1],
                    y[doPlot][-1] + vs,
                    int(mixrat[i]),
                    color=c5,
                    ha='center',
                    va='bottom',
                    backgroundcolor='w')
    """
    6. Add sounding data
    """
    # 6.1 Temperature and dewpoint temperature
    if (si.T.size > 0):
        y = skewty(si.p)
        x1 = skewtx(si.T - T0, y)
        x2 = skewtx(si.Td - T0, y)

        pl.plot(x1, y, '-', color=cT, linewidth=2)
        pl.plot(x2, y, '-', color=cTd, linewidth=2)

    # 6.2 Add height labels to axis
    if (si.z.size > 0 and si.z.size == si.p.size):
        y = skewty(si.p)
        p_last = 1e9
        for k in range(si.z.size):
            if (y[k] <= y11 and np.abs(si.p[k] - p_last) > dp_label):
                pl.text(x11 + hs,
                        y[k],
                        str(int(si.z[k])) + 'm',
                        color=c2,
                        ha='right',
                        va='center',
                        size=7,
                        backgroundcolor='w')
                p_last = si.p[k]

    # 6.2 Wind barbs
    if (si.u.size > 0):
        y = skewty(si.p)
        u = si.u * 1.95
        v = si.v * 1.95
        xb = x11 + 9 * hs

        p_last = 1e9
        for k in range(si.z.size):
            if (y[k] <= y11 and np.abs(si.p[k] - p_last) > dp_label):
                pl.barbs(xb,
                         y[k],
                         u[k],
                         v[k],
                         length=5.2,
                         linewidth=0.5,
                         pivot='middle')
                p_last = si.p[k]
    """
    6.1 :) Try to add measured data
    """
    # 6.1 Temperature and dewpoint temperature
    if (si.Tm.size > 0):
        y = skewty(si.pm)
        x1 = skewtx(si.Tm, y)
        x2 = skewtx(si.Tdm, y)

        pl.plot(x1, y, '--', color=cT, linewidth=1)
        pl.plot(x2, y, '--', color=cTd, linewidth=1)
    """
    7. Lauch parcel
    """
    if (si.parcel == True):
        # Plot starting position:
        p0s = skewty(si.ps)
        T0s = skewtx(si.Ts - T0, p0s)
        Td0s = skewtx(Td(si.rs, si.ps) - T0, p0s)
        pl.scatter(T0s, p0s, facecolor='none')
        pl.scatter(Td0s, p0s, facecolor='none')

        # Lists to hold parcel pressure, temp and dewpoint temp during ascent
        pp = [si.ps]
        Tp = [si.Ts]
        Tdp = [Td(si.rs, si.ps)]

        # Launch parcel
        n = 0
        while (Tp[-1] > Tdp[-1] and n < 1000):
            n += 1
            dp2 = max(1, (Tp[-1] - Tdp[-1]) * 300)  # bit weird, but fast
            pp.append(pp[-1] - dp2)
            Tp.append(si.Ts * exner(pp[-1], si.ps))
            Tdp.append(Td(si.rs, pp[-1]))

        # Plot lines from surface --> LCL
        ps = skewty(np.array(pp))
        Tps = skewtx(np.array(Tp) - T0, ps)
        Tdps = skewtx(np.array(Tdp) - T0, ps)
        pl.plot(Tps, ps, 'k', linewidth=1.5, dashes=[4, 2])
        pl.plot(Tdps, ps, 'k', linewidth=1.5, dashes=[4, 2])
        pl.scatter(Tps[-1], ps[-1], facecolor='none')

        # Iteratively find the moist adiabat starting at p0, which goes through the temperature at LCL
        Ths = si.Ts / exner(si.ps, p0)  # potential temperature surface (@p0)
        ThwsLCL = dsatlftskewt(
            Ths - T0, pp[-1]) + T0  # Temp moist adiabat at plcl, through Ths
        thw0 = Ths - (ThwsLCL - Tp[-1]
                      )  # First estimate of moist adiabat passing through Tlcl

        ThwLCL = dsatlftskewt(thw0 - T0, pp[-1]) + T0
        while (np.abs(ThwLCL - Tp[-1]) > 0.1):
            thw0 -= ThwLCL - Tp[-1]
            ThwLCL = dsatlftskewt(thw0 - T0, pp[-1]) + T0

        # Plot moist adiabat from LCL upwards
        p = np.arange(pp[-1], ptop, -dp)
        x = np.zeros(p.size)
        y = np.zeros(p.size)
        for k in range(p.size):
            thw = dsatlftskewt(thw0 - T0, p[k])
            y[k] = skewty(p[k])
            x[k] = skewtx(thw, y[k])

        pl.plot(x, y, 'k', linewidth=1.5, dashes=[4, 2])
    """
    Add info from TEMF boundary layer scheme
    """
    if (si.Tu.size > 0):
        # Cloud fraction
        dw = (x11 - x00)  # width of diagram
        y = skewty(si.p)
        x = x00 + si.cfru * 0.2 * (x11 - x00)
        pl.plot(x, y, '-', linewidth=1.5, color=c6)  # cloud cover

        cfr_pos = np.where(si.cfru > 0.001)[0]
        if (np.size(cfr_pos) > 1):
            pl.text(x00,
                    y[cfr_pos[0] - 1],
                    '- %im' % (si.z[cfr_pos[0] - 1]),
                    ha='left',
                    va='center',
                    size=8,
                    color=c6)
            pl.text(x00,
                    y[cfr_pos[-1]],
                    '- %im' % (si.z[cfr_pos[-1]]),
                    ha='left',
                    va='center',
                    size=8,
                    color=c6)
            kmax = np.where(si.cfru == si.cfru.max())[0][0]
            pl.text(x.max(),
                    y[kmax],
                    '- %i%%' % (si.cfru[kmax] * 100.),
                    ha='left',
                    va='center',
                    size=8,
                    color=c6)
    """
    6. Finish diagram
    """
    pl.xticks([])
    pl.yticks([])
    pl.box('off')
    pl.xlim(x00 - 0.1, x11 + 16 * hs)
    pl.ylim(y00 - 0.1, y11 + 0.1)

    # draw axis
    pl.plot([x00, x11], [y00, y00], 'k-')
    pl.plot([x00, x00], [y00, y11], 'k-')

    pl.figtext(0.5, 0.05, 'Temperature (C)', ha='center')
    pl.figtext(0.015, 0.52, 'Pressure (hPa)', rotation=90)
    label = 'Skew-T log-P, %s, %s UTC' % (si.name, si.time)
    pl.figtext(0.5, 0.97, label, ha='center')

    if (olga != -1):
        img = image.imread(olga.olgaRoot + 'include/olga_left.png')
        pl.figimage(img, 7, 5)
        #pl.figimage(img,10,olga.fig_width_px-45)
        pl.figtext(0.99, 0.011, '%s' % olga.map_desc[0], size=7, ha='right')

    return fig
def plot_ua_vvel(press):
	print("    %smb VVEL" % press)
	level = levid[str(press)]

	#Set Figure Size (1000 x 800)
	pylab.figure(figsize=(width,height),frameon=False)
	
	cdict_vvel ={'red':	((0.00, 0.50, 0.50),
				(0.10, 1.00, 1.00),
				(0.20, 1.00, 1.00),
				(0.35, 1.00, 1.00),
				(0.40, 1.00, 1.00),
				(0.45, 0.80, 0.80),
				(0.50, 0.72, 0.72),
				(0.55, 0.68, 0.68),
				(0.60, 0.64, 0.64),
				(0.65, 0.60, 0.70),
				(0.70, 0.40, 0.45),
				(0.80, 0.20, 0.20),
				(0.90, 0.00, 0.00),
				(1.00, 0.00, 0.00)),

		'green':	((0.00, 0.35, 0.35),
				(0.10, 0.45, 0.45),
				(0.20, 0.55, 0.55),
				(0.35, 1.00, 1.00),
				(0.40, 1.00, 1.00),
				(0.45, 1.00, 1.00),
				(0.50, 1.00, 1.00),
				(0.55, 1.00, 1.00),
				(0.60, 1.00, 1.00),
				(0.65, 1.00, 1.00),
				(0.70, 1.00, 1.00),
				(0.80, 1.00, 1.00),
				(0.90, 1.00, 1.00),
				(1.00, 0.80, 0.80)),

		'blue':		((0.00, 0.00, 0.00),
				(0.10, 0.00, 0.00),
				(0.20, 0.20, 0.20),
				(0.35, 1.00, 1.00),
				(0.40, 1.00, 1.00),
				(0.45, 1.00, 1.00),
				(0.50, 1.00, 1.00),
				(0.55, 1.00, 1.00),
				(0.60, 1.00, 1.00),
				(0.65, 1.00, 1.00),
				(0.70, 1.00, 1.00),
				(0.80, 1.00, 1.00),
				(0.90, 1.00, 1.00),
				(1.00, 0.80, 0.80))}

	vvel_coltbl = LinearSegmentedColormap('VVEL_COLTBL',cdict_vvel)

	vert_vel = np.multiply(w_wind_ua[time,level],100)	
	vert_vel = np.nan_to_num(vert_vel)

	VVEL=pylab.contourf(x,y,vert_vel,vvel_clevs,cmap=vvel_coltbl,extend='both')

	# Contour the heights

	heights=hght_clevs[contlevid[str(press)]]
	phtotal = np.add(phb[time,level],ph[time,level])
	gheight = np.divide(phtotal, 9.81)
	#gheight = ght[time,level]

	HGHT=pylab.contour(x,y,gheight,heights,colors='k',linewidths=1.5)
	pylab.clabel(HGHT,inline=1,fontsize=8,fmt='%1.0f',inline_spacing=1)


	# Convert winds from m/s to kts and then draw barbs	
	u_wind_kts = u_wind_ms_ua[time,level] * 1.94384449
	v_wind_kts = v_wind_ms_ua[time,level] * 1.94384449


	pylab.barbs(x_th,y_th,u_wind_kts[::thin,::thin],\
		v_wind_kts[::thin,::thin], length=5, sizes={'spacing':0.2},pivot='middle')


	title = '%s mb VVel, Height (m), Wind (kts)' % press
	prodid = '%smb_vert_vel' % press
	units = "cm/s"

	drawmap(VVEL, title, prodid, units)
def plot_ua_rhum(press):
	print("    %smb RHUM" % press)
	level = levid[str(press)]

	#Set Figure Size (1000 x 800)
	pylab.figure(figsize=(width,height),frameon=False)
	heights=hght_clevs[contlevid[str(press)]]


	cdict =	{'red':		((0.00, 0.76, 0.76),
				(0.25, 0.64, 0.64),
				(0.50, 0.52, 0.52),
				(0.75, 0.42, 0.42),
				(1.00, 0.32, 0.32)),

		'green':	((0.00, 0.90, 0.90),
				(0.25, 0.80, 0.80),
				(0.50, 0.70, 0.70),
				(0.75, 0.60, 0.60),
				(1.00, 0.50, 0.50)),

		'blue':		((0.00, 0.49, 0.49),
				(0.25, 0.32, 0.32),
				(0.50, 0.17, 0.17),
				(0.75, 0.06, 0.06),
				(1.00, 0.05, 0.05))}

	 
	rhum_coltbl = LinearSegmentedColormap('RHUM_COLTBL',cdict)

	# Temperature calculation here
	
	#TC = temps_ua[time,level] - 273
	TH_K = np.add(temps_ua[time,level],temps_base_ua)
	TK = np.multiply(TH_K,math.pow((float(press)/1000.),(287.04/1004.))) 
	TC = TK - 273

	# RHUM Calculation here
	es = 6.112*np.exp(17.67*TC/(TC+243.5))
	w = np.divide(qvap[time,level],(1-qvap[time,level]))
	e = (w*float(press))/(0.622+w)
	relh = e / es * 100.

	RHUM=pylab.contourf(x,y,relh,rhum_clevs,extend='max',cmap=rhum_coltbl)
	
	# Contour the heights

	phtotal = np.add(phb[time,level],ph[time,level])
	gheight = np.divide(phtotal, 9.81)
	#gheight = ght[time,level]
	HGHT=pylab.contour(x,y,gheight,heights,colors='k',linewidths=1.5)
	pylab.clabel(HGHT,inline=1,fontsize=8,fmt='%1.0f',inline_spacing=1)


	# Convert winds from m/s to kts and then draw barbs	
	u_wind_kts = u_wind_ms_ua[time,level] * 1.94384449
	v_wind_kts = v_wind_ms_ua[time,level] * 1.94384449
	

	pylab.barbs(x_th,y_th,u_wind_kts[::thin,::thin],\
		v_wind_kts[::thin,::thin], length=5, sizes={'spacing':0.2},pivot='middle')

	title = '%s mb RELH, Height (m), Wind (kts)' % press
	prodid = '%smb_rel_hum' % press
	units = "percent"

	drawmap(RHUM, title, prodid, units)
def plot_ua_avort(press):
    print("    %smb VORICITY" % press)
    level = levid[str(press)]
    #Set Figure Size (1000 x 800)
    pylab.figure(figsize=(width, height), frameon=False)
    cdict_vort = {
        'red': ((0.00, 1.00, 1.00), (0.10, 1.00, 1.00), (0.25, 1.00, 1.00),
                (0.35, 0.82, 0.82), (0.40, 0.63, 0.63), (0.45, 0.00, 0.00),
                (0.50, 0.12, 0.12), (0.60, 0.00, 0.00), (0.70, 0.25, 0.25),
                (0.85, 0.50, 0.50), (1.00, 0.65, 0.65)),
        'green': ((0.00, 0.43, 0.43), (0.10, 0.88, 0.88), (0.25, 1.00, 1.00),
                  (0.35, 0.96, 0.96), (0.40, 0.82, 0.82), (0.45, 0.75, 0.75),
                  (0.50, 0.56, 0.56), (0.60, 0.41, 0.41), (0.70, 0.00, 0.00),
                  (0.85, 0.00, 0.00), (1.00, 0.13, 0.13)),
        'blue': ((0.00, 0.00, 0.00), (0.10, 0.20, 0.20), (0.25, 1.00, 1.00),
                 (0.35, 1.00, 1.00), (0.40, 1.00, 1.00), (0.45, 1.00, 1.00),
                 (0.50, 1.00, 1.00), (0.60, 0.88, 0.88), (0.70, 0.80, 0.80),
                 (0.85, 0.59, 0.59), (1.00, 0.94, 0.94))
    }

    vort_coltbl = LinearSegmentedColormap('VORT_COLTBL', cdict_vort)

    # Vorticity calculation goes here
    dx_2 = 2 * dx
    dy_2 = 2 * dy
    for xs in range(x_dim - 2):
        cur_column = []
        for ys in range(y_dim - 2):
            du = np.subtract(u_wind_ms_ua[time, level, (ys + 1), (xs + 2)],
                             u_wind_ms_ua[time, level, (ys + 1), xs])
            dv = np.subtract(v_wind_ms_ua[time, level, (ys + 2), (xs + 1)],
                             v_wind_ms_ua[time, level, ys, (xs + 1)])
            f_val = f[time, (ys + 1), (xs + 1)]
            cur_avort = (dv / dx_2) - (du / dy_2) + f_val
            cur_column.append(cur_avort)
            np_column = np.array(cur_column)

        if xs == 0:
            vort_grid = np_column
        else:
            vort_grid = np.column_stack((vort_grid, np_column))

    avort = np.multiply(vort_grid, 100000)
    #np.reshape(avort,-1)
    avort = np.nan_to_num(avort)
    VORT = pylab.contourf(x_1,
                          y_1,
                          avort,
                          vort_clevs,
                          cmap=vort_coltbl,
                          extend='both')

    # Contour the heights

    heights = hght_clevs[contlevid[str(press)]]
    phtotal = np.add(phb[time, level], ph[time, level])
    gheight = np.divide(phtotal, 9.81)
    #gheight = ght[time,level]

    HGHT = pylab.contour(x, y, gheight, heights, colors='k', linewidths=1.5)
    pylab.clabel(HGHT, inline=1, fontsize=8, fmt='%1.0f', inline_spacing=1)

    # Convert winds from m/s to kts and then draw barbs
    u_wind_kts = u_wind_ms_ua[time, level] * 1.94384449
    v_wind_kts = v_wind_ms_ua[time, level] * 1.94384449


    pylab.barbs(x_th,y_th,u_wind_kts[::thin,::thin],\
     v_wind_kts[::thin,::thin], length=5, sizes={'spacing':0.2},pivot='middle')

    title = '%s mb avort (10^-5 s-1) Height, Wind (kts)' % press
    prodid = '%smb_vort' % press
    units = "10^-5 / s"

    drawmap(VORT, title, prodid, units)
def plot_ua_avort(press):
	print("    %smb VORICITY" % press)
	level = levid[str(press)]
	#Set Figure Size (1000 x 800)
	pylab.figure(figsize=(width,height),frameon=False)
	cdict_vort ={'red':	((0.00, 1.00, 1.00),
				(0.10, 1.00, 1.00),
				(0.25, 1.00, 1.00),
				(0.35, 0.82, 0.82),
				(0.40, 0.63, 0.63),
				(0.45, 0.00, 0.00),
				(0.50, 0.12, 0.12),
				(0.60, 0.00, 0.00),
				(0.70, 0.25, 0.25),
				(0.85, 0.50, 0.50),
				(1.00, 0.65, 0.65)),

		'green':	((0.00, 0.43, 0.43),
				(0.10, 0.88, 0.88),
				(0.25, 1.00, 1.00),
				(0.35, 0.96, 0.96),
				(0.40, 0.82, 0.82),
				(0.45, 0.75, 0.75),
				(0.50, 0.56, 0.56),
				(0.60, 0.41, 0.41),
				(0.70, 0.00, 0.00),
				(0.85, 0.00, 0.00),
				(1.00, 0.13, 0.13)),

		'blue':		((0.00, 0.00, 0.00),
				(0.10, 0.20, 0.20),
				(0.25, 1.00, 1.00),
				(0.35, 1.00, 1.00),
				(0.40, 1.00, 1.00),
				(0.45, 1.00, 1.00),
				(0.50, 1.00, 1.00),
				(0.60, 0.88, 0.88),
				(0.70, 0.80, 0.80),
				(0.85, 0.59, 0.59),
				(1.00, 0.94, 0.94))}
	
	vort_coltbl = LinearSegmentedColormap('VORT_COLTBL',cdict_vort)

	# Vorticity calculation goes here
	dx_2 = 2 * dx
	dy_2 = 2 * dy
	for xs in range(x_dim - 2):
		cur_column = []
		for ys in range(y_dim - 2):
			du = np.subtract(u_wind_ms_ua[time,level,(ys+1),(xs+2)],u_wind_ms_ua[time,level,(ys+1),xs]) 
			dv = np.subtract(v_wind_ms_ua[time,level,(ys+2),(xs+1)],v_wind_ms_ua[time,level,ys,(xs+1)])
			f_val = f[time,(ys+1),(xs+1)]
			cur_avort = (dv/dx_2) - (du/dy_2) + f_val
			cur_column.append(cur_avort)
			np_column=np.array(cur_column)

		if xs == 0:
			vort_grid=np_column
		else:
			vort_grid = np.column_stack((vort_grid,np_column)) 
			
	avort = np.multiply(vort_grid, 100000)
	#np.reshape(avort,-1)
	avort = np.nan_to_num(avort)
	VORT=pylab.contourf(x_1,y_1,avort,vort_clevs,cmap=vort_coltbl, extend='both')

	# Contour the heights

	heights=hght_clevs[contlevid[str(press)]]
	phtotal = np.add(phb[time,level],ph[time,level])
	gheight = np.divide(phtotal, 9.81)
	#gheight = ght[time,level]

	HGHT=pylab.contour(x,y,gheight,heights,colors='k',linewidths=1.5)
	pylab.clabel(HGHT,inline=1,fontsize=8,fmt='%1.0f',inline_spacing=1)


	# Convert winds from m/s to kts and then draw barbs	
	u_wind_kts = u_wind_ms_ua[time,level] * 1.94384449
	v_wind_kts = v_wind_ms_ua[time,level] * 1.94384449


	pylab.barbs(x_th,y_th,u_wind_kts[::thin,::thin],\
		v_wind_kts[::thin,::thin], length=5, sizes={'spacing':0.2},pivot='middle')


	title = '%s mb avort (10^-5 s-1) Height, Wind (kts)' % press
	prodid = '%smb_vort' % press
	units = "10^-5 / s"

	drawmap(VORT, title, prodid, units)
        pylab.gca().add_line(Line2D([x + rad, x - rad], [y, y], color='k', linewidth=line_width, solid_capstyle='butt'))
    return

if __name__ == "__main__":
    l_scale = .01
    oktas = 2
    pylab.figure(figsize=(12, 8))
    pylab.axes((0, 0, 1, 1))

    map = Basemap(resolution='i', projection='stere', lat_ts=60., 
        lat_0=60., lon_0=-97.5,
        llcrnrlat=30.0, llcrnrlon=-106.0,
        urcrnrlat=40.0, urcrnrlon=-93.0)
    unit_scale = l_scale * max(map.urcrnry - map.llcrnry, map.urcrnrx - map.llcrnrx)

    map.drawcoastlines()
    map.drawcountries()
    map.drawstates()

    point = map(-97.4167, 35.2167)

    drawSkyCover(point, .7 * unit_scale, oktas)
#   drawRSDPrecip(_vec_add(point, (-1.5 * unit_scale, 0)), '+', .3 * unit_scale, snow=True, rain=True, intermittent=False)
#   drawFreezingPrecip(_vec_add(point, (-2 * unit_scale, 0)), '-', 'drizzle', 1.5 * unit_scale)
#   drawThunderPrecip(_vec_add(point, (-1.5 * unit_scale, 0)), '-', 'hail', .8 * unit_scale)
#   drawPelletSymbol(_vec_add(point, (-1.5 * unit_scale, 0)), .8 * unit_scale, sleet=True)
    drawSkyObscuration(_vec_add(point, (-1.5 * unit_scale, 0)), .5 * unit_scale, freezing=True)
    pylab.barbs(point[0], point[1], 5., 10.)

    pylab.savefig("mpl_test.png")