In [ ]:
"""

Load pp, plot and save
8km difference

"""

import os, sys


#%matplotlib inline
#%pylab inline

import matplotlib

matplotlib.use('Agg') 
# Must be before importing matplotlib.pyplot or pylab!
from matplotlib import rc
from matplotlib.font_manager import FontProperties
from matplotlib import rcParams

from mpl_toolkits.basemap import Basemap

rc('font', family = 'serif', serif = 'cmr10')
rc('text', usetex=True)

rcParams['text.usetex']=True
rcParams['text.latex.unicode']=True
rcParams['font.family']='serif'
rcParams['font.serif']='cmr10'

import matplotlib.pyplot as plt
#from matplotlib import figure
import matplotlib as mpl
import matplotlib.cm as mpl_cm
import numpy as np

import iris
import iris.coords as coords
import iris.quickplot as qplt
import iris.plot as iplt
import iris.coord_categorisation
import iris.unit as unit

import cartopy.crs as ccrs
import cartopy.io.img_tiles as cimgt
import matplotlib.ticker as mticker
from cartopy.mpl.gridliner import LONGITUDE_FORMATTER, LATITUDE_FORMATTER

import datetime
from mpl_toolkits.basemap import cm

import imp
from textwrap import wrap

import re

import iris.analysis.cartography

import math

from dateutil import tz

#import multiprocessing as mp

import gc

import types

import pdb

save_path='/nfs/a90/eepdw/Figures/EMBRACE/'

model_name_convert_title = imp.load_source('util', '/nfs/see-fs-01_users/eepdw/python_scripts/modules/model_name_convert_title.py')
unrotate = imp.load_source('util', '/nfs/see-fs-01_users/eepdw/python_scripts/modules/unrotate_pole.py')
#pp_file = ''
plot_diags=['temp', 'sp_hum']
plot_levels = [925, 850, 700, 500] 

experiment_ids = ['dklyu']
#experiment_ids = ['djzny', 'djznq', 'djzns', 'dkjxq', 'dklyu', 'dkmbq', 'dklwu', 'dklzq', 'dkbhu', 'djznu', 'dkhgu' ] # All 12

difference_id = 'dkmbq'

pp_file_path = '/nfs/a90/eepdw/Data/EMBRACE/'

diffidmin1 = difference_id[:-1]

degs_crop_top = 1.7
degs_crop_bottom = 2.5

from iris.coord_categorisation import add_categorised_coord

def add_hour_of_day(cube, coord, name='hour'):
    add_categorised_coord(cube, name, coord,
          lambda coord, x: coord.units.num2date(x).hour)

figprops = dict(figsize=(8,8), dpi=100)

#cmap=cm.s3pcpn_l


u = unit.Unit('hours since 1970-01-01 00:00:00',calendar='gregorian')
dx, dy = 10, 10

divisor=10  # for lat/lon rounding

lon_high = 101.866 
lon_low = 64.115
lat_high = 33.
lat_low =-6.79

lon_low_tick=lon_low -(lon_low%divisor)
lon_high_tick=math.ceil(lon_high/divisor)*divisor

lat_low_tick=lat_low - (lat_low%divisor)
lat_high_tick=math.ceil(lat_high/divisor)*divisor


def main():
  
 
#experiment_ids = ['djznw', 'djzny', 'djznq', 'djzns', 'dkjxq', 'dklyu', 'dkmbq', 'dklwu', 'dklzq', 'dkbhu', 'djznu', 'dkhgu' ] # All 12
 #experiment_ids = ['djzny', 'djzns', 'djznw', 'dkjxq', 'dklyu', 'dkmbq', 'dklwu', 'dklzq' ] 
 #experiment_ids = ['djzny', 'djzns', 'djznu', 'dkbhu', 'dkjxq', 'dklyu', 'dkmbq', 'dklwu', 'dklzq', 'dkhgu'] 
 #experiment_ids = ['djzns', 'djznu', 'dkbhu', 'dkjxq', 'dklyu', 'dkmbq', 'dklwu', 'dklzq', 'dkhgu'] 
 #experiment_ids = ['dklzq', 'dkmbq', 'dkjxq', 'dklwu', 'dklyu', 'djzns']
#experiment_ids = ['djzns' ] 
 #experiment_ids = ['dkhgu','dkjxq']
 
    for p_level in plot_levels:

        # Set pressure height contour min/max
        if p_level == 925:
            clevgh_min = -32.
            clevgh_max = 32.
        elif p_level == 850:
            clevgh_min = -24.
            clev_max = 24.
        elif p_level == 700:
            clevgh_min = -24.
            clev_max = 24.
        elif p_level == 500:
            clevgh_min = -24.
            clevgh_max = 24.
        else:
            print 'Contour min/max not set for this pressure level'

# Set potential temperature min/max       
        if p_level == 925:
            clevpt_min = -3.
            clevpt_max = 100.
        elif p_level == 850:
            clevpt_min = -3.
            clevpt_max = 3.
        elif p_level == 700:
            clevpt_min = -3.
            clevpt_max = 3.
        elif p_level == 500:
            clevpt_min = -3.
            clevpt_max = 3.
        else:
            print 'Potential temperature min/max not set for this pressure level'

 # Set specific humidity min/max       
        if p_level == 925:
            clevsh_min = -0.0025
            clevsh_max = 0.0025
        elif p_level == 850:
            clevsh_min = -0.0025
            clevsh_max = 0.0025
        elif p_level == 700:
            clevsh_min = -0.0025
            clevsh_max = 0.0025
        elif p_level == 500:
            clevsh_min = -0.0025
            clevsh_max = 0.0025
        else:
            print 'Specific humidity min/max not set for this pressure level'

        clevs_lin = np.linspace(clevgh_min, clevgh_max, num=32)


        p_level_constraint = iris.Constraint(pressure=p_level)
        
        
        pp_file_height_diff = '%s_408_on_p_levs_mean_by_hour.pp' % (difference_id)
        pfile_height_diff = '%s%s/%s/%s' % (pp_file_path, diffidmin1, difference_id, pp_file_height_diff)
         
        height_cube_diff = iris.load_cube(pfile_height_diff, p_level_constraint )

        for plot_diag in plot_diags:
            
            pp_file_diff = '%s_%s_on_p_levs_mean_by_hour.pp' % (difference_id, plot_diag)
            pfile_diff = '%s%s/%s/%s' % (pp_file_path, diffidmin1, difference_id, pp_file_diff)
            
            cube_diff = iris.load_cube(pfile_diff, p_level_constraint )
        
            for experiment_id in experiment_ids:
            
                expmin1 = experiment_id[:-1]

                pp_file = '%s_%s_on_p_levs_mean_by_hour.pp' % (experiment_id, plot_diag)
                pfile = '%s%s/%s/%s' % (pp_file_path, expmin1, experiment_id, pp_file)
                pcube = iris.load_cube(pfile, p_level_constraint)
                #cube=iris.analysis.maths.multiply(pcube,3600)
                # For each hour in cube

                height_pp_file = '%s_408_on_p_levs_mean_by_hour.pp' % (experiment_id)
                height_pfile = '%s%s/%s/%s' % (pp_file_path, expmin1, experiment_id, height_pp_file)
                height_cube = iris.load_cube(height_pfile, p_level_constraint)

                #time_coords = cube_f.coord('time')
                add_hour_of_day(pcube, pcube.coord('time'))
                add_hour_of_day(cube_diff, cube_diff.coord('time'))
                add_hour_of_day(height_cube, height_cube.coord('time'))
                add_hour_of_day(height_cube_diff, height_cube_diff.coord('time'))

                #pcube.remove_coord('time')
                #cube_diff.remove_coord('time')
                #height_cube.remove_coord('time')
                #height_cube_diff.remove_coord('time')

                #p_cube_difference = iris.analysis.maths.subtract(pcube, cube_diff, dim='hour')
                #height_cube_difference = iris.analysis.maths.subtract(height_cube, height_cube_diff, dim='hour')
                
                #pdb.set_trace()

                #del height_cube, pcube, height_cube_diff, cube_diff

                for t, time_cube in enumerate(pcube.slices(['grid_latitude', 'grid_longitude'])):
                            
                    #pdb.set_trace()
                
                    print time_cube
                    time_cube_408 = height_cube.extract(iris.Constraint(hour=time_cube.coord('hour').points))
            
                    # Get  time of averagesfor plot title
  

                    h = u.num2date(np.array(time_cube.coord('hour').points, dtype=float)[0]).strftime('%H%M')


                    #Convert to India time

                    from_zone = tz.gettz('UTC')
                    to_zone = tz.gettz('Asia/Kolkata')
                    
                    h_utc = u.num2date(np.array(time_cube.coord('hour').points, dtype=float)[0]).replace(tzinfo=from_zone)
                   
                    h_local = h_utc.astimezone(to_zone).strftime('%H%M')
                
                    fig = plt.figure(**figprops)
         
                    cmap=plt.cm.RdBu_r
                    
                    ax = plt.axes(projection=ccrs.PlateCarree(), extent=(lon_low,lon_high,lat_low+degs_crop_bottom,lat_high-degs_crop_top))
                    
                    m =\
                        Basemap(llcrnrlon=lon_low,llcrnrlat=lat_low,urcrnrlon=lon_high,urcrnrlat=lat_high, rsphere = 6371229)
                    #pdb.set_trace()
                    lat = p_cube_difference.coord('grid_latitude').points
                    lon = p_cube_difference.coord('grid_longitude').points
                    
                    cs = p_cube_difference.coord_system('CoordSystem')
                    
                    lons, lats = np.meshgrid(lon, lat) 
                    lons, lats = iris.analysis.cartography.unrotate_pole\
                                (lons,lats, cs.grid_north_pole_longitude, cs.grid_north_pole_latitude)
                    
                    
                    x,y = m(lons,lats)
                    
                    
                    if plot_diag=='temp':
                        min_contour = clevpt_min
                        max_contour = clevpt_max
                        cb_label='K' 
                        main_title='8km  Explicit model (dklyu) minus 8km parametrised model geopotential height (grey contours), potential temperature (colours),\
                                          and wind (vectors) %s UTC    %s IST' % (h, h_local)
                        tick_interval=1
                    elif plot_diag=='sp_hum':
                        min_contour = clevsh_min
                        max_contour = clevsh_max 
                        cb_label='kg/kg' 
                        main_title='8km  Explicit model (dklyu) minus 8km parametrised model geopotential height (grey contours), specific humidity (colours),\
                                         and wind (vectors) %s-%s UTC    %s-%s IST' % (h, h_local)
                        tick_interval=0.0005
                        
                    clevs = np.linspace(min_contour, max_contour, 32)
                    clevs = np.linspace(-3, 3, 32)
                    cont = plt.contourf(x,y,p_cube.data, clevs, cmap=cmap, extend='both')
                    
                    
                    #cont = iplt.contourf(time_cube, cmap=cmap, extend='both')
                    

                    cs_lin = iplt.contour(time_cube_408, clevs_lin,colors='#262626',linewidths=1.)
                    plt.clabel(cs_lin, fontsize=14, fmt='%d', color='black')
                    
                    #del time_cube
                     
                    #plt.clabel(cont, fmt='%d')
                    #ax.stock_img()
                    ax.coastlines(resolution='110m', color='#262626') 
                     
                    gl = ax.gridlines(draw_labels=True,linewidth=0.5, color='#262626', alpha=0.5, linestyle='--')
                    gl.xlabels_top = False
                    gl.ylabels_right = False
                    #gl.xlines = False
                    dx, dy = 10, 10

                    gl.xlocator = mticker.FixedLocator(range(int(lon_low_tick),int(lon_high_tick)+dx,dx))
                    gl.ylocator = mticker.FixedLocator(range(int(lat_low_tick),int(lat_high_tick)+dy,dy))
                    gl.xformatter = LONGITUDE_FORMATTER
                    gl.yformatter = LATITUDE_FORMATTER
                    
                    gl.xlabel_style = {'size': 12, 'color':'#262626'}
                    #gl.xlabel_style = {'color': '#262626', 'weight': 'bold'}
                    gl.ylabel_style = {'size': 12, 'color':'#262626'}         
                    
                    cbar = fig.colorbar(cont, orientation='horizontal', pad=0.05, extend='both')
                    cbar.set_label('%s' % cb_label, fontsize=10, color='#262626') 
                    #cbar.set_label(time_cube.units, fontsize=10, color='#262626')
                    cbar.set_ticks(np.arange(min_contour, max_contour+tick_interval,tick_interval))
                    ticks = (np.arange(min_contour, max_contour+tick_interval,tick_interval))
                    cbar.set_ticklabels(['${%.1f}$' % i for i in ticks])
                    
                    cbar.ax.tick_params(labelsize=10, color='#262626')
                    
                    
                    #main_title='Mean Rainfall for EMBRACE Period -%s UTC (%s IST)' % (h, h_local)
                    #main_title=time_cube.standard_name.title().replace('_',' ')
                    #model_info = re.sub(r'[(\']', ' ', model_info)
                    #model_info = re.sub(r'[\',)]', ' ', model_info)
                    #print model_info
                    
                    file_save_name = '%s_%s_%s_' % (experiment_id, plot_diag, p_level)
                    save_dir = '%s%s/%s' % (save_path, experiment_id, plot_diag)
                    if not os.path.exists('%s' % save_dir): os.makedirs('%s' % (save_dir))
                    
                    #plt.show()

                    fig.savefig('%s/%s_notitle.png' % (save_dir, file_save_name), format='png', bbox_inches='tight')
                    
                    
                    plt.title('%s UTC %s IST' % (h, h_local))
                    fig.savefig('%s/%s_short_title.png' % (save_dir, file_save_name) , format='png', bbox_inches='tight')
                    
                    
                    model_info=re.sub('(.{68} )', '\\1\n', str(model_name_convert_title.main(experiment_id)), 0, re.DOTALL)
                    plt.title('\n'.join(wrap('%s\n%s' % (main_title, model_info), 1000,replace_whitespace=False)), fontsize=16)               
                    fig.savefig('%s/%s.png' % (save_dir, file_save_name), format='png', bbox_inches='tight')
 
                    fig.clf()
                    plt.close()
                    #del time_cube
                    gc.collect()


if __name__ == '__main__':
   main()
    #proc=mp.Process(target=worker)
    #proc.daemon=True
    #proc.start()
    #proc.join()

In [5]:
"""

Load pp, plot and save
8km not difference

"""

import os, sys


#%matplotlib inline
#%pylab inline

import matplotlib

matplotlib.use('Agg') 
# Must be before importing matplotlib.pyplot or pylab!
from matplotlib import rc
from matplotlib.font_manager import FontProperties
from matplotlib import rcParams

from mpl_toolkits.basemap import Basemap

rc('font', family = 'serif', serif = 'cmr10')
rc('text', usetex=True)

rcParams['text.usetex']=True
rcParams['text.latex.unicode']=True
rcParams['font.family']='serif'
rcParams['font.serif']='cmr10'

import matplotlib.pyplot as plt
#from matplotlib import figure
import matplotlib as mpl
import matplotlib.cm as mpl_cm
import numpy as np

import iris
import iris.coords as coords
import iris.quickplot as qplt
import iris.plot as iplt
import iris.coord_categorisation
import iris.unit as unit

import cartopy.crs as ccrs
import cartopy.io.img_tiles as cimgt
import matplotlib.ticker as mticker
from cartopy.mpl.gridliner import LONGITUDE_FORMATTER, LATITUDE_FORMATTER

import datetime
from mpl_toolkits.basemap import cm

import imp
from textwrap import wrap

import re

import iris.analysis.cartography

import math

from dateutil import tz

#import multiprocessing as mp

import gc

import types

import pdb

save_path='/nfs/a90/eepdw/Figures/EMBRACE/'

model_name_convert_title = imp.load_source('util', '/nfs/see-fs-01_users/eepdw/python_scripts/modules/model_name_convert_title.py')
unrotate = imp.load_source('util', '/nfs/see-fs-01_users/eepdw/python_scripts/modules/unrotate_pole.py')
#pp_file = ''
plot_diags=['temp', 'sp_hum']
plot_levels = [925, 850, 700, 500] 

experiment_ids = ['dklyu', 'dkmbq' ]
#experiment_ids = ['djzny', 'djznq', 'djzns', 'dkjxq', 'dklyu', 'dkmbq', 'dklwu', 'dklzq', 'dkbhu', 'djznu', 'dkhgu' ] # All 12



pp_file_path = '/nfs/a90/eepdw/Data/EMBRACE/'

degs_crop_top = 1.7
degs_crop_bottom = 2.5

from iris.coord_categorisation import add_categorised_coord

def add_hour_of_day(cube, coord, name='hour'):
    add_categorised_coord(cube, name, coord,
          lambda coord, x: coord.units.num2date(x).hour)

figprops = dict(figsize=(8,8), dpi=100)

#cmap=cm.s3pcpn_l


u = unit.Unit('hours since 1970-01-01 00:00:00',calendar='gregorian')
dx, dy = 10, 10

divisor=10  # for lat/lon rounding

lon_high = 101.866 
lon_low = 64.115
lat_high = 33.
lat_low =-6.79

lon_low_tick=lon_low -(lon_low%divisor)
lon_high_tick=math.ceil(lon_high/divisor)*divisor

lat_low_tick=lat_low - (lat_low%divisor)
lat_high_tick=math.ceil(lat_high/divisor)*divisor


def main():
  
 
#experiment_ids = ['djznw', 'djzny', 'djznq', 'djzns', 'dkjxq', 'dklyu', 'dkmbq', 'dklwu', 'dklzq', 'dkbhu', 'djznu', 'dkhgu' ] # All 12
 #experiment_ids = ['djzny', 'djzns', 'djznw', 'dkjxq', 'dklyu', 'dkmbq', 'dklwu', 'dklzq' ] 
 #experiment_ids = ['djzny', 'djzns', 'djznu', 'dkbhu', 'dkjxq', 'dklyu', 'dkmbq', 'dklwu', 'dklzq', 'dkhgu'] 
 #experiment_ids = ['djzns', 'djznu', 'dkbhu', 'dkjxq', 'dklyu', 'dkmbq', 'dklwu', 'dklzq', 'dkhgu'] 
 #experiment_ids = ['dklzq', 'dkmbq', 'dkjxq', 'dklwu', 'dklyu', 'djzns']
#experiment_ids = ['djzns' ] 
 #experiment_ids = ['dkhgu','dkjxq']
 
    for p in plot_levels:

# Set pressure height contour min/max
        if p == 925:
            clev_min = 680.
            clev_max = 810.
        elif p == 850:
            clev_min = 1435.
            clev_max = 1530.
        elif p == 700:
            clev_min = 3090.
            clev_max = 3155.
        elif p == 500:
            clev_min = 5800.
            clev_max = 5890.
        else:
            print 'Contour min/max not set for this pressure level'

# Set potential temperature min/max       
        if p == 925:
            clevpt_min = 298.
            clevpt_max = 310.
        elif p == 850:
            clevpt_min = 302.
            clevpt_max = 312.
        elif p == 700:
            clevpt_min = 312.
            clevpt_max = 320.
        elif p == 500:
            clevpt_min = 325.
            clevpt_max = 332.
        else:
            print 'Potential temperature min/max not set for this pressure level'


  # Set specific humidity min/max       
        if p == 925:
            clevsh_min = 0.012
            clevsh_max = 0.020
        elif p == 850:
            clevsh_min = 0.007
            clevsh_max = 0.017
        elif p == 700:
            clevsh_min = 0.002
            clevsh_max = 0.010
        elif p == 500:
            clevsh_min = 0.001
            clevsh_max = 0.005
        else:
            print 'Specific humidity min/max not set for this pressure level'
       

        #clevs_col = np.arange(clev_min, clev_max)
        clevs_lin = np.linspace(clev_min, clev_max, num=20)    

        p_level_constraint = iris.Constraint(pressure=p)      

        for plot_diag in plot_diags:    

            for experiment_id in experiment_ids:
            
                expmin1 = experiment_id[:-1]

                pp_file = '%s_%s_on_p_levs_mean_by_hour.pp' % (experiment_id, plot_diag)
                pfile = '%s%s/%s/%s' % (pp_file_path, expmin1, experiment_id, pp_file)
                pcube = iris.load_cube(pfile, p_level_constraint)
                #cube=iris.analysis.maths.multiply(pcube,3600)
                # For each hour in cube

                height_pp_file = '%s_408_on_p_levs_mean_by_hour.pp' % (experiment_id)
                height_pfile = '%s%s/%s/%s' % (pp_file_path, expmin1, experiment_id, height_pp_file)
                height_cube = iris.load_cube(height_pfile, p_level_constraint)
                
                print pcube
                print height_cube

                #time_coords = cube_f.coord('time')
                add_hour_of_day(pcube, pcube.coord('time'))
            
                add_hour_of_day(height_cube, height_cube.coord('time'))

                #pcube.remove_coord('time')
                #cube_diff.remove_coord('time')
                #height_cube.remove_coord('time')
                #height_cube_diff.remove_coord('time')

                #p_cube_difference = iris.analysis.maths.subtract(pcube, cube_diff, dim='hour')
                #height_cube_difference = iris.analysis.maths.subtract(height_cube, height_cube_diff, dim='hour')
                
                #pdb.set_trace()

                #del height_cube, pcube, height_cube_diff, cube_diff

                for t, time_cube in enumerate(pcube.slices(['grid_latitude', 'grid_longitude'])):
                                   
                    
                    #pdb.set_trace()
                
                    print time_cube
                    time_cube_408 = height_cube.extract(iris.Constraint(hour=time_cube.coord('hour').points))
                    
                    # Get  time of averagesfor plot title
  

                    h = u.num2date(np.array(time_cube.coord('hour').points, dtype=float)[0]).strftime('%H%M')

                    #Convert to India time

                    from_zone = tz.gettz('UTC')
                    to_zone = tz.gettz('Asia/Kolkata')
                    
                    h_utc = u.num2date(np.array(time_cube.coord('hour').points, dtype=float)[0]).replace(tzinfo=from_zone)
                   
                    h_local = h_utc.astimezone(to_zone).strftime('%H%M')
                
                    fig = plt.figure(**figprops)
         
                    cmap=plt.cm.RdBu_r
                    
                    ax = plt.axes(projection=ccrs.PlateCarree(), extent=(lon_low,lon_high,lat_low+degs_crop_bottom,lat_high-degs_crop_top))
                    
                    m =\
                        Basemap(llcrnrlon=lon_low,llcrnrlat=lat_low,urcrnrlon=lon_high,urcrnrlat=lat_high, rsphere = 6371229)
                    #pdb.set_trace()
                    lat = pcube.coord('grid_latitude').points
                    lon = pcube.coord('grid_longitude').points
                    
                    cs = pcube.coord_system('CoordSystem')
                    
                    lons, lats = np.meshgrid(lon, lat) 
                    lons, lats = iris.analysis.cartography.unrotate_pole\
                                (lons,lats, cs.grid_north_pole_longitude, cs.grid_north_pole_latitude)
                    
                    
                    x,y = m(lons,lats)
                    
                    
                    if plot_diag=='temp':
                        min_contour = clevpt_min
                        max_contour = clevpt_max
                        cb_label='K' 
                        main_title='8km  Explicit model (dklyu) minus 8km parametrised model geopotential height (grey contours), potential temperature (colours),\
                                          and wind (vectors) %s UTC    %s IST' % (h, h_local)
                        tick_interval=1
                    elif plot_diag=='sp_hum':
                        min_contour = clevsh_min
                        max_contour = clevsh_max 
                        cb_label='kg/kg' 
                        main_title='8km  Explicit model (dklyu) minus 8km parametrised model geopotential height (grey contours), specific humidity (colours),\
                                         and wind (vectors) %s-%s UTC    %s-%s IST' % (h, h_local)
                        tick_interval=0.0005
                        
                    clevs = np.linspace(min_contour, max_contour, 32)
                    clevs = np.linspace(-3, 3, 32)
                    cont = plt.contourf(x,y,time_cube.data, clevs, cmap=cmap, extend='both')
                    
                    
                    #cont = iplt.contourf(time_cube, cmap=cmap, extend='both')
                    

                    cs_lin = iplt.contour(time_cube_408, clevs_lin,colors='#262626',linewidths=1.)
                    plt.clabel(cs_lin, fontsize=14, fmt='%d', color='black')
                    
                    #del time_cube
                     
                    #plt.clabel(cont, fmt='%d')
                    #ax.stock_img()
                    ax.coastlines(resolution='110m', color='#262626') 
                     
                    gl = ax.gridlines(draw_labels=True,linewidth=0.5, color='#262626', alpha=0.5, linestyle='--')
                    gl.xlabels_top = False
                    gl.ylabels_right = False
                    #gl.xlines = False
                    dx, dy = 10, 10

                    gl.xlocator = mticker.FixedLocator(range(int(lon_low_tick),int(lon_high_tick)+dx,dx))
                    gl.ylocator = mticker.FixedLocator(range(int(lat_low_tick),int(lat_high_tick)+dy,dy))
                    gl.xformatter = LONGITUDE_FORMATTER
                    gl.yformatter = LATITUDE_FORMATTER
                    
                    gl.xlabel_style = {'size': 12, 'color':'#262626'}
                    #gl.xlabel_style = {'color': '#262626', 'weight': 'bold'}
                    gl.ylabel_style = {'size': 12, 'color':'#262626'}         
                    
                    cbar = fig.colorbar(cont, orientation='horizontal', pad=0.05, extend='both')
                    cbar.set_label('%s' % cb_label, fontsize=10, color='#262626') 
                    #cbar.set_label(time_cube.units, fontsize=10, color='#262626')
                    cbar.set_ticks(np.arange(min_contour, max_contour+tick_interval,tick_interval))
                    ticks = (np.arange(min_contour, max_contour+tick_interval,tick_interval))
                    cbar.set_ticklabels(['${%.1f}$' % i for i in ticks])
                    
                    cbar.ax.tick_params(labelsize=10, color='#262626')
                    
                    
                    #main_title='Mean Rainfall for EMBRACE Period -%s UTC (%s IST)' % (h, h_local)
                    #main_title=time_cube.standard_name.title().replace('_',' ')
                    #model_info = re.sub(r'[(\']', ' ', model_info)
                    #model_info = re.sub(r'[\',)]', ' ', model_info)
                    #print model_info
                    
                    file_save_name = '%s_%s_%s_%s' % (experiment_id, plot_diag, p, h)
                    save_dir = '%s%s/%s' % (save_path, experiment_id, plot_diag)
                    if not os.path.exists('%s' % save_dir): os.makedirs('%s' % (save_dir))
                    
                    #plt.show()

                    fig.savefig('%s/%s_notitle.png' % (save_dir, file_save_name), format='png', bbox_inches='tight')
                    
                    
                    plt.title('%s UTC %s IST' % (h, h_local))
                    fig.savefig('%s/%s_short_title.png' % (save_dir, file_save_name) , format='png', bbox_inches='tight')
                    
                    
                    model_info=re.sub('(.{68} )', '\\1\n', str(model_name_convert_title.main(experiment_id)), 0, re.DOTALL)
                    plt.title('\n'.join(wrap('%s\n%s' % (main_title, model_info), 1000,replace_whitespace=False)), fontsize=16)               
                    fig.savefig('%s/%s.png' % (save_dir, file_save_name), format='png', bbox_inches='tight')
 
                    fig.clf()
                    plt.close()
                    #del time_cube
                    gc.collect()


if __name__ == '__main__':
   main()
    #proc=mp.Process(target=worker)
    #proc.daemon=True
    #proc.start()
    #proc.join()


unknown / (unknown)                 (time: 24; grid_latitude: 600; grid_longitude: 600)
     Dimension coordinates:
          time                           x                  -                    -
          grid_latitude                  -                  x                    -
          grid_longitude                 -                  -                    x
     Scalar coordinates:
          pressure: 925.0 hPa
unknown / (unknown)                 (time: 24; grid_latitude: 600; grid_longitude: 600)
     Dimension coordinates:
          time                           x                  -                    -
          grid_latitude                  -                  x                    -
          grid_longitude                 -                  -                    x
     Scalar coordinates:
          pressure: 925.0 hPa
unknown / (unknown)                 (grid_latitude: 600; grid_longitude: 600)
     Dimension coordinates:
          grid_latitude                           x                    -
          grid_longitude                          -                    x
     Scalar coordinates:
          hour: 0
          pressure: 925.0 hPa
          time: 2011-08-19 00:00:00
unknown / (unknown)                 (grid_latitude: 600; grid_longitude: 600)
     Dimension coordinates:
          grid_latitude                           x                    -
          grid_longitude                          -                    x
     Scalar coordinates:
          hour: 7
          pressure: 925.0 hPa
          time: 2011-08-19 07:00:00
unknown / (unknown)                 (grid_latitude: 600; grid_longitude: 600)
     Dimension coordinates:
          grid_latitude                           x                    -
          grid_longitude                          -                    x
     Scalar coordinates:
          hour: 8
          pressure: 925.0 hPa
          time: 2011-08-19 08:00:00
unknown / (unknown)                 (grid_latitude: 600; grid_longitude: 600)
     Dimension coordinates:
          grid_latitude                           x                    -
          grid_longitude                          -                    x
     Scalar coordinates:
          hour: 9
          pressure: 925.0 hPa
          time: 2011-08-19 09:00:00
unknown / (unknown)                 (grid_latitude: 600; grid_longitude: 600)
     Dimension coordinates:
          grid_latitude                           x                    -
          grid_longitude                          -                    x
     Scalar coordinates:
          hour: 10
          pressure: 925.0 hPa
          time: 2011-08-19 10:00:00
unknown / (unknown)                 (grid_latitude: 600; grid_longitude: 600)
     Dimension coordinates:
          grid_latitude                           x                    -
          grid_longitude                          -                    x
     Scalar coordinates:
          hour: 11
          pressure: 925.0 hPa
          time: 2011-08-19 11:00:00
unknown / (unknown)                 (grid_latitude: 600; grid_longitude: 600)
     Dimension coordinates:
          grid_latitude                           x                    -
          grid_longitude                          -                    x
     Scalar coordinates:
          hour: 12
          pressure: 925.0 hPa
          time: 2011-08-19 12:00:00
---------------------------------------------------------------------------
KeyboardInterrupt                         Traceback (most recent call last)
<ipython-input-5-e8536f536eab> in <module>()
    347 
    348 if __name__ == '__main__':
--> 349    main()
    350     #proc=mp.Process(target=worker)
    351     #proc.daemon=True

<ipython-input-5-e8536f536eab> in main()
    329                     #plt.show()
    330 
--> 331                     fig.savefig('%s/%s_notitle.png' % (save_dir, file_save_name), format='png', bbox_inches='tight')
    332 
    333 

/nfs/see-fs-01_users/eepdw/.local/lib/python2.7/site-packages/matplotlib-1.4.0-py2.7-linux-x86_64.egg/matplotlib/figure.pyc in savefig(self, *args, **kwargs)
   1468             self.set_frameon(frameon)
   1469 
-> 1470         self.canvas.print_figure(*args, **kwargs)
   1471 
   1472         if frameon:

/nfs/see-fs-01_users/eepdw/.local/lib/python2.7/site-packages/matplotlib-1.4.0-py2.7-linux-x86_64.egg/matplotlib/backend_bases.pyc in print_figure(self, filename, dpi, facecolor, edgecolor, orientation, format, **kwargs)
   2137                     orientation=orientation,
   2138                     dryrun=True,
-> 2139                     **kwargs)
   2140                 renderer = self.figure._cachedRenderer
   2141                 bbox_inches = self.figure.get_tightbbox(renderer)

/nfs/see-fs-01_users/eepdw/.local/lib/python2.7/site-packages/matplotlib-1.4.0-py2.7-linux-x86_64.egg/matplotlib/backends/backend_agg.pyc in print_png(self, filename_or_obj, *args, **kwargs)
    511 
    512     def print_png(self, filename_or_obj, *args, **kwargs):
--> 513         FigureCanvasAgg.draw(self)
    514         renderer = self.get_renderer()
    515         original_dpi = renderer.dpi

/nfs/see-fs-01_users/eepdw/.local/lib/python2.7/site-packages/matplotlib-1.4.0-py2.7-linux-x86_64.egg/matplotlib/backends/backend_agg.pyc in draw(self)
    459 
    460         try:
--> 461             self.figure.draw(self.renderer)
    462         finally:
    463             RendererAgg.lock.release()

/nfs/see-fs-01_users/eepdw/.local/lib/python2.7/site-packages/matplotlib-1.4.0-py2.7-linux-x86_64.egg/matplotlib/artist.pyc in draw_wrapper(artist, renderer, *args, **kwargs)
     57     def draw_wrapper(artist, renderer, *args, **kwargs):
     58         before(artist, renderer)
---> 59         draw(artist, renderer, *args, **kwargs)
     60         after(artist, renderer)
     61 

/nfs/see-fs-01_users/eepdw/.local/lib/python2.7/site-packages/matplotlib-1.4.0-py2.7-linux-x86_64.egg/matplotlib/figure.pyc in draw(self, renderer)
   1077         dsu.sort(key=itemgetter(0))
   1078         for zorder, a, func, args in dsu:
-> 1079             func(*args)
   1080 
   1081         renderer.close_group('figure')

/nfs/see-fs-01_users/eepdw/.local/lib/python2.7/site-packages/matplotlib-1.4.0-py2.7-linux-x86_64.egg/matplotlib/artist.pyc in draw_wrapper(artist, renderer, *args, **kwargs)
     57     def draw_wrapper(artist, renderer, *args, **kwargs):
     58         before(artist, renderer)
---> 59         draw(artist, renderer, *args, **kwargs)
     60         after(artist, renderer)
     61 

/apps/python-libs-1.2/lib/cartopy/mpl/geoaxes.py in draw(self, renderer, inframe)
    337 
    338         return matplotlib.axes.Axes.draw(self, renderer=renderer,
--> 339                                          inframe=inframe)
    340 
    341     def __str__(self):

/nfs/see-fs-01_users/eepdw/.local/lib/python2.7/site-packages/matplotlib-1.4.0-py2.7-linux-x86_64.egg/matplotlib/artist.pyc in draw_wrapper(artist, renderer, *args, **kwargs)
     57     def draw_wrapper(artist, renderer, *args, **kwargs):
     58         before(artist, renderer)
---> 59         draw(artist, renderer, *args, **kwargs)
     60         after(artist, renderer)
     61 

/nfs/see-fs-01_users/eepdw/.local/lib/python2.7/site-packages/matplotlib-1.4.0-py2.7-linux-x86_64.egg/matplotlib/axes/_base.pyc in draw(self, renderer, inframe)
   2090 
   2091         for zorder, a in dsu:
-> 2092             a.draw(renderer)
   2093 
   2094         renderer.close_group('axes')

/nfs/see-fs-01_users/eepdw/.local/lib/python2.7/site-packages/matplotlib-1.4.0-py2.7-linux-x86_64.egg/matplotlib/artist.pyc in draw_wrapper(artist, renderer, *args, **kwargs)
     57     def draw_wrapper(artist, renderer, *args, **kwargs):
     58         before(artist, renderer)
---> 59         draw(artist, renderer, *args, **kwargs)
     60         after(artist, renderer)
     61 

/nfs/see-fs-01_users/eepdw/.local/lib/python2.7/site-packages/matplotlib-1.4.0-py2.7-linux-x86_64.egg/matplotlib/collections.pyc in draw(self, renderer)
    256         self.update_scalarmappable()
    257 
--> 258         transform, transOffset, offsets, paths = self._prepare_points()
    259 
    260         gc = renderer.new_gc()

/nfs/see-fs-01_users/eepdw/.local/lib/python2.7/site-packages/matplotlib-1.4.0-py2.7-linux-x86_64.egg/matplotlib/collections.pyc in _prepare_points(self)
    234         if not transform.is_affine:
    235             paths = [transform.transform_path_non_affine(path)
--> 236                      for path in paths]
    237             transform = transform.get_affine()
    238         if not transOffset.is_affine:

/nfs/see-fs-01_users/eepdw/.local/lib/python2.7/site-packages/matplotlib-1.4.0-py2.7-linux-x86_64.egg/matplotlib/transforms.pyc in transform_path_non_affine(self, path)
   2265             return path
   2266         elif not self._a.is_affine and self._b.is_affine:
-> 2267             return self._a.transform_path_non_affine(path)
   2268         else:
   2269             return self._b.transform_path_non_affine(

/apps/python-libs-1.2/lib/cartopy/mpl/geoaxes.py in transform_path_non_affine(self, src_path)
    167         for geom in geoms:
    168             proj_geom = self.target_projection.project_geometry(
--> 169                 geom, self.source_projection)
    170             transformed_geoms.append(proj_geom)
    171 

/apps/python-libs-1.2/lib/cartopy/crs.pyc in project_geometry(self, geometry, src_crs)
    155             raise ValueError('Unsupported geometry '
    156                              'type {!r}'.format(geom_type))
--> 157         return getattr(self, method_name)(geometry, src_crs)
    158 
    159     def _project_point(self, point, src_crs):

/apps/python-libs-1.2/lib/cartopy/crs.pyc in _project_polygon(self, polygon, src_crs)
    293         # Resolve all the inside vs. outside rings, and convert to the
    294         # final MultiPolygon.
--> 295         return self._rings_to_multi_polygon(rings, is_ccw)
    296 
    297     def _attach_lines_to_boundary(self, multi_line_strings, is_ccw):

/apps/python-libs-1.2/lib/cartopy/crs.pyc in _rings_to_multi_polygon(self, rings, is_ccw)
    427         interior_rings = []
    428         for ring in rings:
--> 429             if ring.is_ccw != is_ccw:
    430                 interior_rings.append(ring)
    431             else:

/apps/canopy-1.4.1/Enthought/Canopy_64bit/User/lib/python2.7/site-packages/shapely/geometry/polygon.py in is_ccw(self)
     73     def is_ccw(self):
     74         """True is the ring is oriented counter clock-wise"""
---> 75         return bool(self.impl['is_ccw'](self))
     76 
     77     @property

/apps/canopy-1.4.1/Enthought/Canopy_64bit/User/lib/python2.7/site-packages/shapely/algorithms/cga.py in is_ccw_op(ring)
     12     """Predicate implementation"""
     13     def is_ccw_op(ring):
---> 14         return signed_area(ring) >= 0.0
     15     return is_ccw_op
     16 

/apps/canopy-1.4.1/Enthought/Canopy_64bit/User/lib/python2.7/site-packages/shapely/algorithms/cga.py in signed_area(ring)
      4     algorithm at: http://www.cgafaq.info/wiki/Polygon_Area.
      5     """
----> 6     xs, ys = ring.coords.xy
      7     xs.append(xs[1])
      8     ys.append(ys[1])

/apps/canopy-1.4.1/Enthought/Canopy_64bit/User/lib/python2.7/site-packages/shapely/geometry/base.py in _get_coords(self)
    268     def _get_coords(self):
    269         """Access to geometry's coordinates (CoordinateSequence)"""
--> 270         if self.is_empty:
    271             return []
    272         return CoordinateSequence(self)

KeyboardInterrupt: 

In [ ]:
experiment_id='dklyu'
plot_diag='temp'
expmin1='dkly'
difference_id='dkmbq'
diffidmin1='dkmb'
pp_file = '%s_%s_on_p_levs_mean_by_hour.pp' % (experiment_id, plot_diag)
pfile = '%s%s/%s/%s' % (pp_file_path, expmin1, experiment_id, pp_file)
pcube = iris.load_cube(pfile, p_level_constraint)

In [ ]:
pcube.data[(pcube.data<0)].shape

In [ ]:
pcube.data.flatten().shape

In [ ]:
p_level=925
p_level_constraint = iris.Constraint(pressure=p_level)

pp_file_diff = '%s_%s_on_p_levs_mean_by_hour.pp' % (difference_id, plot_diag)
pfile_diff = '%s%s/%s/%s' % (pp_file_path, diffidmin1, difference_id, pp_file_diff)

cube_diff = iris.load_cube(pfile_diff, p_level_constraint )

In [ ]:
cube_diff[0].data

In [ ]:
di=pcube[0]-cube_diff[0]

In [ ]:
plt.contourf(pcube[0].data, np.linspace(290, 315,32))
plt.colorbar()

In [ ]:
plt.contourf(cube_diff[0].data, np.linspace(290, 315,32))
plt.colorbar()

In [ ]:
plt.contourf(di.data, np.linspace(-3, 3,32))
plt.colorbar()

In [ ]:
pcube.coord('hour').points