# -*- coding: iso-8859-15 -*- # Python tools to plot netCDF files. # From L. Fita work in different places: LMD (France) # More information at: http://www.xn--llusfb-5va.cat/python/PyNCplot # # pyNCplot and its component drawing_tools.py comes with ABSOLUTELY NO WARRANTY. # This work is licendes under a Creative Commons # Attribution-ShareAlike 4.0 International License (http://creativecommons.org/licenses/by-sa/4.0) # #import pylab as plt # From http://stackoverflow.com/questions/13336823/matplotlib-python-error import numpy as np import matplotlib as mpl mpl.use('Agg') from matplotlib.pylab import * import matplotlib.pyplot as plt from mpl_toolkits.basemap import Basemap import os from netCDF4 import Dataset as NetCDFFile import nc_var_tools as ncvar import generic_tools as gen errormsg = 'ERROR -- error -- ERROR -- error' warnmsg = 'WARNING -- waring -- WARNING -- warning' fillValue = 1.e20 fillValueF = 1.e20 colorsauto = ['#FF0000', '#00FF00', '#0000FF', '#FF00FF', '#00FFFF', '#FFAA00', \ '#AA0000', '#00AA00', '#0000AA', '#AA00AA', '#00AAAA', '#AA3200', '#AA0032', \ '#32AA00', '#3200AA', '#00AA32', '#0032AA', '#32FF00', '#3200FF', '#0032FF', \ '#FF3200', '#FF0032', '#00FF32', '#323200', '#320032', '#003232'] # USGS land types usgscolors = {1: ['Urban and Built-Up Land', 'k', (0.8, 0.8, 0.8, 1.)], \ 2: ['Dryland Cropland and Pasture', 'y', (0.2, 0.9, 0., 1.)], \ 3: ['Irrigated Cropland and Pasture', 'g', (0.1, 0.9, 0., 1.)], \ 4: ['Mixed Dryland/Irrigated Cropland and Pasture', 'g', (0.15, 0.9, 0., 1.)], \ 5: ['Cropland/Grassland Mosaic', 'y', (0.1, 0.9, 0.1, 1.)], \ 6: ['Cropland/Woodland Mosaic', 'y', (0.3, 0.9, 0., 1.)], \ 7: ['Grassland', 'g', (0., 1., 0.5, 1.)], \ 8: ['Shrubland', 'y', (0.5, 0.6, 0., 1.)], \ 9: ['Mixed Shrubland/Grassland', 'y', (0.3, 0.7, 0., 1.)], \ 10: ['Savanna', 'y', (0.6, 0.6, 0., 1.)], \ 11: ['Deciduous Broadleaf Forest', 'g', (0., 0.4, 0., 1.)], \ 12: ['Deciduous Needleleaf Forest', 'g', (0., 0.5, 0., 1.)], \ 13: ['Evergreen Broadleaf Forest', 'g', (0., 0.55, 0., 1.)], \ 14: ['Evergreen Needleleaf Forest', 'g', (0., 0.6, 0., 1.)], \ 15: ['Mixed Forest', 'g', (0., 0.57, 0., 1.)], \ 16: ['Water Bodies', 'b', (0.1, 0.1, 1., 1.)], \ 17: ['Herbaceous Wetland', 'b', (0.1, 0.1, 1., 1.)], \ 18: ['Wooded Wetland', 'g', (0., 0.8, 0., 1.)], \ 19: ['Barren or Sparsely Vegetated', 'c', (0.8, 0.6, 0., 1.)], \ 20: ['Herbaceous Tundra', 'c', (0.6, 0.9, 0., 1.)], \ 21: ['Wooded Tundra', 'c', (0.7, 0.9, 0., 1.)], \ 22: ['Mixed Tundra', 'c', (0.65, 0.9, 0., 1.)], \ 23: ['Bare Ground Tundra', 'c', (0.9, 0.5, 0., 1.)], \ 24: ['Snow or Ice', 'w', (0.95, 0.95, 0.95, 1.)], \ 25: ['Playa', 'y', (0.95, 0.95, 0., 1.)], \ 26: ['Lava', 'y', (0.95, 0.1, 0.1, 1.)], \ 27: ['White Sand', 'y', (0.9, 0.9, 0.7, 1.)], \ 28: ['Unassigned', 'k', (0.05, 0.05, 0.05, 1.)], \ 29: ['Unassigned', 'k', (0.1, 0.1, 0.1, 1.)], \ 30: ['Unassigned', 'k', (0.15, 0.15, 0.15, 1.)], \ 31: ['Low Intensity Residential', 'k', (0.5, 0.5, 0.5, 1.)], \ 32: ['High Intensity Residential', 'k', (0.7, 0.7, 0.7, 1.)], \ 33: ['Industrial or Commercial', 'k', (0.9, 0.9, 0.9, 1.)]} # MODIFIED_IGBP_MODIS_NOAH land types modigbpmodisnoahcolors = {1: ['Evergreen Needleleaf Forest', 'g', (0.2, 0.9, 0.2, 1.)], \ 2: ['Evergreen Broadleaf Forest', 'g', (0.15, 0.8, 0.15, 1.)], \ 3: ['Deciduous Needleleaf Forest', 'g', (0.10, 0.8, 0.10, 1.)], \ 4: ['Deciduous Broadleaf Forest', 'g', (0.17, 0.8, 0.17, 1.)], \ 5: ['Mixed Forests', 'g', (0.7, 0.9, 0.1, 1.)], \ 6: ['Closed Shrublands', 'g', (0.6, 0.75, 0.1, 1.)], \ 7: ['Open Shrublands', 'g', (0.65, 0.75, 0.3, 1.)], \ 8: ['Woody Savannas', 'g', (0.75, 0.35, 0.1, 1.)], \ 9: ['Savannas', 'g', (0.70, 0.3, 0.10, 1.)], \ 10: ['Grasslands', 'g', (0.85, 0.9, 0.85, 1.)], \ 11: ['Permanent wetlands', 'g', (0.25, 0.25, 0.6, 1.)], \ 12: ['Croplands', 'g', (0.80, 0.9, 0.80, 1.)], \ 13: ['Urban and Built-Up', 'k', (0.2, 0.2, 0.2, 1.)], \ 14: ['cropland/natural vegetation mosaic', 'g', (0.70, 0.9, 0.70, 1.)], \ 15: ['Snow and Ice', 'w', (0.90, 0.9, 0.90, 1.)], \ 16: ['Barren or Sparsely Vegetated', 'w', (0.90, 0.6, 0.20, 1.)], \ 17: ['Water', 'g', (0.2, 0.89, 0.89, 1.)], \ 18: ['Wooded Tundra', 'g', (0.7, 0.3, 0.1, 1.)], \ 19: ['Mixed Tundra', 'g', (0.65, 0.25, 0.1, 1.)], \ 20: ['Barren Tundra', 'g', (0.45, 0.05, 0.1, 1.)], \ 21: ['Unassigned', 'w', (0.05, 0.05, 0.05, 1.)], \ 22: ['Unassigned', 'w', (0.05, 0.05, 0.05, 1.)], \ 23: ['Unassigned', 'w', (0.05, 0.05, 0.05, 1.)], \ 24: ['Unassigned', 'w', (0.05, 0.05, 0.05, 1.)], \ 25: ['Unassigned', 'w', (0.05, 0.05, 0.05, 1.)], \ 26: ['Unassigned', 'w', (0.05, 0.05, 0.05, 1.)], \ 27: ['Unassigned', 'w', (0.05, 0.05, 0.05, 1.)], \ 28: ['Unassigned', 'w', (0.05, 0.05, 0.05, 1.)], \ 29: ['Unassigned', 'w', (0.05, 0.05, 0.05, 1.)], \ 30: ['Unassigned', 'w', (0.05, 0.05, 0.05, 1.)], \ 31: ['Low Intensity Residential', 'k', (0.30, 0.3, 0.3, 1.)], \ 32: ['High Intensity Residential', 'k', (0.15, 0.15, 0.15, 1.)], \ 33: ['Industrial or Commercial', 'k', (0.25, 0.25, 0.25, 1.)]} ncolorsauto = ['r', 'g', 'b', 'c', 'm', 'y', 'k', 'w', \ 'r', 'g', 'b', 'c', 'm', 'y', 'k', 'w', \ 'r', 'g', 'b', 'c', 'm', 'y', 'k', 'w', \ 'r', 'g', 'b', 'c', 'm', 'y', 'k', 'w',] rgbacolorsauto = [(1.,0.,0.,1.), (0.,1.,0.,1.), (0.,0.,1.,1.), (1.,0.,1.,1.), \ (0.,1.,1.,1.), (1.,0.,1.,1.), (1., 0.5, 0., 1.), (0.5, 0., 0., 1.), \ (0., 0.5, 0., 1.), (0., 0., 0.5, 1.), (0.5, 0., 0.5, 1.), (0., 0.5, 0.5, 1.), \ (0.5, 0.25, 0., 1.), (0.5, 0., 0.25, 1.), (0.25, 0.5, 0., 1.), (0.25, 0., 0.5, 1.),\ (0., 0.5, 0.25, 1.), (0., 0.25, 0.5, 1.), (0.5, 1., 0., 1.), (0.5, 0., 1., 1.), \ (0., 0.5, 1., 1.), (1., 0.25, 0., 1.), (1., 0., 0.25, 1.), (0., 1., 0.25, 1.), \ (0.25, 0.25, 0., 1.), (0.25, 0., 0.25, 1.), (0., 0.25, 0.25, 1.)] pointkindsauto = ['.', 'x', '+', '*', '|', '_', '1', '2', '3', '4', 'o', '<', '>', \ 'v', '^', 's', 'D', 'p' ,'h' ,'H'] linekindsauto = ['-', '--', '-.', ':'] linewidthsauto = [1.] pointsizesauto = [7.] ####### Functions # check_colorBar: Check if the given colorbar exists in matplotlib # colorbar_vals: Function to provide the colorbar values for a figure # format_axes: Function to provide the format for the ticks of the axes in a figure # graphic_range: Function to provide the ranges of a figure following different options # legend_values: Function to determine the values for the legend # searchInlist: # datetimeStr_datetime: # dateStr_date: # numVector_String: # timeref_datetime: # slice_variable: Function to return a slice of a given variable according to values to its dimension # interpolate_locs: # datetimeStr_conversion: # percendone: # netCDFdatetime_realdatetime: # file_nlines: # variables_values: # units_lunits: Function to provide LaTeX equivalences from a given units # ASCII_LaTeX: # DegGradSec_deg: # intT2dt: # lonlat2D: Function to return lon, lat 2D matrices from any lon,lat matrix # lonlat_values: # date_CFtime: # pot_values: Function to modify a seies of values by their potency of 10 # CFtimes_plot: # color_lines: # output_kind: # check_arguments: # Str_Bool: # movie_2D_shadow: Plot of a 2D field with shadow # multi_plot_2D_shadow: plot of multiple 2D shadowing variables sharing colorbar # pixelgrid: Function to provide the kind of grid distribution for a plot # plot_points: # plot_2Dfield: # plot_2Dfield_easy: # plot_topo_geogrid: # plot_topo_geogrid_boxes: # plot_2D_shadow: Plot of a 2D field with shadow # plot_2D_shadow_time: Plotting a 2D field with one of the axes being time # plot_Neighbourghood_evol:Plotting neighbourghood evolution # plot_time_lag: Function to plot a time-lag figure (x, previous values; y, future values) # plot_Trajectories # plot_2Dshad_obssim: Function to plot a 2D shadding plot with comparison # between observations (as filled colored circles) and simulation (shadded # continuous field) # plot_2Dshad_obssim_time: Function to plot a 2D shadding plot with comparison # between observations (as filled colored circles) and simulation (shadded # continuous field) with a time-axis # plot_2D_shadow_contour: # plot_2D_shadow_2contour: Plotting 3 2D fields, 1 with shadow and two with contour lines # plot_2D_shadow_contour_time: # dxdy_lonlat: Function to provide lon/lat 2D lilke-matrices from any sort of dx,dy values # plot_2D_shadow_line: # plot_2lines: Function to plot two lines in different axes (x/x2 or y/y2) # plot_2lines_time: Function to plot two time-lines in different axes (x/x2 or y/y2) # plot_bars: Function to plot a bar plot with multiple columns # plot_bars_line: Function to plot a bar and lines plot with multiple columns # plot_bars_time: Function to plot a bar plot with multiple columns with time axis # plot_bars_line: Function to plot a bar and lines plot with multiple columns with a time-axis # plot_cycle: Function to plot a variale with a circular cycle # plot_lines: Function to plot a collection of lines # plot_SkewT: Function to plot a SkewT-logP diagram using matplotlib's API example # plot_Taylor: Function to draw a Taylor diagram (Taylor 2001) # plot_TimeEnsembles: Function to plot a of an Ensemble of values with a time-axis # plot_WindRose: Function to plot a wind rose (from where the dinw blows) # plot_ZQradii: Function to plot following radial averages only at exact grid poins # transform: Function to transform the values and the axes # From nc_var_tools.py def reduce_spaces(string): """ Function to give words of a line of text removing any extra space """ values = string.replace('\n','').split(' ') vals = [] for val in values: if len(val) > 0: vals.append(val) return vals def searchInlist(listname, nameFind): """ Function to search a value within a list listname = list nameFind = value to find >>> searInlist(['1', '2', '3', '5'], '5') True """ for x in listname: if x == nameFind: return True break return False def datetimeStr_datetime(StringDT): """ Function to transform a string date ([YYYY]-[MM]-[DD]_[HH]:[MI]:[SS] format) to a date object >>> datetimeStr_datetime('1976-02-17_00:00:00') 1976-02-17 00:00:00 """ import datetime as dt fname = 'datetimeStr_datetime' dateD = np.zeros((3), dtype=int) timeT = np.zeros((3), dtype=int) # quit() dateD[0] = int(StringDT[0:4]) dateD[1] = int(StringDT[5:7]) dateD[2] = int(StringDT[8:10]) trefT = StringDT.find(':') if not trefT == -1: # print ' ' + fname + ': refdate with time!' timeT[0] = int(StringDT[11:13]) timeT[1] = int(StringDT[14:16]) timeT[2] = int(StringDT[17:19]) if int(dateD[0]) == 0: print warnmsg print ' ' + fname + ': 0 reference year!! changing to 1' dateD[0] = 1 newdatetime = dt.datetime(dateD[0], dateD[1], dateD[2], timeT[0], timeT[1], timeT[2]) return newdatetime def dateStr_date(StringDate): """ Function to transform a string date ([YYYY]-[MM]-[DD] format) to a date object >>> dateStr_date('1976-02-17') 1976-02-17 """ import datetime as dt dateD = StringDate.split('-') if int(dateD[0]) == 0: print warnmsg print ' dateStr_date: 0 reference year!! changing to 1' dateD[0] = 1 newdate = dt.date(int(dateD[0]), int(dateD[1]), int(dateD[2])) return newdate def numVector_String(vec,char): """ Function to transform a vector of numbers to a single string [char] separated numVector_String(vec,char) vec= vector with the numerical values char= single character to split the values >>> print numVector_String(np.arange(10),' ') 0 1 2 3 4 5 6 7 8 9 """ fname = 'numVector_String' if vec == 'h': print fname + '_____________________________________________________________' print numVector_String.__doc__ quit() Nvals = len(vec) string='' for i in range(Nvals): if i == 0: string = str(vec[i]) else: string = string + char + str(vec[i]) return string def timeref_datetime(refd, timeval, tu): """ Function to transform from a [timeval] in [tu] units from the time referece [tref] to datetime object refd: time of reference (as datetime object) timeval: time value (as [tu] from [tref]) tu: time units >>> timeref = date(1949,12,1,0,0,0) >>> timeref_datetime(timeref, 229784.36, hours) 1976-02-17 08:21:36 """ import datetime as dt import numpy as np ## Not in timedelta # if tu == 'years': # realdate = refdate + dt.timedelta(years=float(timeval)) # elif tu == 'months': # realdate = refdate + dt.timedelta(months=float(timeval)) if tu == 'weeks': realdate = refd + dt.timedelta(weeks=float(timeval)) elif tu == 'days': realdate = refd + dt.timedelta(days=float(timeval)) elif tu == 'hours': realdate = refd + dt.timedelta(hours=float(timeval)) elif tu == 'minutes': realdate = refd + dt.timedelta(minutes=float(timeval)) elif tu == 'seconds': realdate = refd + dt.timedelta(seconds=float(timeval)) elif tu == 'milliseconds': realdate = refd + dt.timedelta(milliseconds=float(timeval)) else: print errormsg print ' timeref_datetime: time units "' + tu + '" not ready!!!!' quit(-1) return realdate def slice_variable(varobj, dimslice): """ Function to return a slice of a given variable according to values to its dimensions slice_variable(varobj, dims) varobj= object wit the variable dimslice= [[dimname1]:[value1]|[[dimname2]:[value2], ...] pairs of dimension [value]: * [integer]: which value of the dimension * -1: all along the dimension * [beg]:[end] slice from [beg] to [end] * -9: last value of the dimension """ fname = 'slice_variable' if varobj == 'h': print fname + '_____________________________________________________________' print slice_variable.__doc__ quit() vardims = varobj.dimensions Ndimvar = len(vardims) Ndimcut = len(dimslice.split('|')) if Ndimcut == 0: Ndimcut = 1 dimcut = list(dimslice) dimsl = dimslice.split('|') varvalsdim = [] dimnslice = [] monodim = [] for idd in range(Ndimvar): found = False for idc in range(Ndimcut): dimcutn = dimsl[idc].split(':')[0] dimcutv = dimsl[idc].split(':')[1] if vardims[idd] == dimcutn: posfrac = dimcutv.find('@') if posfrac != -1: inifrac = int(dimcutv.split('@')[0]) endfrac = int(dimcutv.split('@')[1]) varvalsdim.append(slice(inifrac,endfrac)) dimnslice.append(vardims[idd]) else: if int(dimcutv) == -1: varvalsdim.append(slice(0,varobj.shape[idd])) dimnslice.append(vardims[idd]) elif int(dimcutv) == -9: varvalsdim.append(varobj.shape[idd]-1) monodim.append(vardims[idd]) else: if int(dimcutv) > varobj.shape[idd]-1: print errormsg print ' ' + fname + ': given value:', int(dimcutv), \ "is larger than length of dimension '" + dimcutn + \ "':", varobj.shape[idd],'(C-like!) !!' quit(-1) varvalsdim.append(int(dimcutv)) monodim.append(vardims[idd]) found = True break if not found and not searchInlist(dimnslice,vardims[idd]) and \ not searchInlist(monodim,vardims[idd]): varvalsdim.append(slice(0,varobj.shape[idd])) dimnslice.append(vardims[idd]) varvalues = varobj[tuple(varvalsdim)] varvalues = np.squeeze(varobj[tuple(varvalsdim)]) return varvalues, dimnslice def get_str_nc(varo, Lchar): """ Function to get string values in a netCDF variable as a chains of 1char values varo= netCDF variable object Lchar = length of the string in the netCDF file """ fname = 'get_str_nc' Nvalues = varo.shape[0] strings = [] for ival in range(Nvalues): stringv = varo[ival,:] string = str('') for ich in range(Lchar): charval = str(stringv[ich:ich+1]).replace('[','').replace(']','').replace("'","") if charval == '--' or len(charval) == 0: break else: if ich == 0: string = charval else: string = string + charval strings.append(string.strip()) return strings def interpolate_locs(locs,coords,kinterp): """ Function to provide interpolate locations on a given axis interpolate_locs(locs,axis,kinterp) locs= locations to interpolate coords= axis values with the reference of coordinates kinterp: kind of interpolation 'lin': linear >>> coordinates = np.arange((10), dtype=np.float) >>> values = np.array([-1.2, 2.4, 5.6, 7.8, 12.0]) >>> interpolate_locs(values,coordinates,'lin') [ -1.2 2.4 5.6 7.8 13. ] >>> coordinates[0] = 0.5 >>> coordinates[2] = 2.5 >>> interpolate_locs(values,coordinates,'lin') [ -3.4 1.93333333 5.6 7.8 13. ] """ fname = 'interpolate_locs' if type(locs) == type('S') and locs == 'h': print fname + '_____________________________________________________________' print interpolate_locs.__doc__ quit() Nlocs = locs.shape[0] Ncoords = coords.shape[0] dcoords = coords[Ncoords-1] - coords[0] intlocs = np.zeros((Nlocs), dtype=np.float) minc = np.min(coords) maxc = np.max(coords) for iloc in range(Nlocs): for icor in range(Ncoords-1): if locs[iloc] < minc and dcoords > 0.: a = 0. b = 1. / (coords[1] - coords[0]) c = coords[0] elif locs[iloc] > maxc and dcoords > 0.: a = (Ncoords-1)*1. b = 1. / (coords[Ncoords-1] - coords[Ncoords-2]) c = coords[Ncoords-2] elif locs[iloc] < minc and dcoords < 0.: a = (Ncoords-1)*1. b = 1. / (coords[Ncoords-1] - coords[Ncoords-2]) c = coords[Ncoords-2] elif locs[iloc] > maxc and dcoords < 0.: a = 0. b = 1. / (coords[1] - coords[0]) c = coords[0] elif locs[iloc] >= coords[icor] and locs[iloc] < coords[icor+1] and dcoords > 0.: a = icor*1. b = 1. / (coords[icor+1] - coords[icor]) c = coords[icor] print coords[icor], locs[iloc], coords[icor+1], ':', icor, '->', a, b elif locs[iloc] <= coords[icor] and locs[iloc] > coords[icor+1] and dcoords < 0.: a = icor*1. b = 1. / (coords[icor+1] - coords[icor]) c = coords[icor] if kinterp == 'lin': intlocs[iloc] = a + (locs[iloc] - c)*b else: print errormsg print ' ' + fname + ": interpolation kind '" + kinterp + "' not ready !!!!!" quit(-1) return intlocs def datetimeStr_conversion(StringDT,typeSi,typeSo): """ Function to transform a string date to an another date object StringDT= string with the date and time typeSi= type of datetime string input typeSo= type of datetime string output [typeSi/o] 'cfTime': [time],[units]; ]time in CF-convention format [units] = [tunits] since [refdate] 'matYmdHMS': numerical vector with [[YYYY], [MM], [DD], [HH], [MI], [SS]] 'YmdHMS': [YYYY][MM][DD][HH][MI][SS] format 'Y-m-d_H:M:S': [YYYY]-[MM]-[DD]_[HH]:[MI]:[SS] format 'Y-m-d H:M:S': [YYYY]-[MM]-[DD] [HH]:[MI]:[SS] format 'Y/m/d H-M-S': [YYYY]/[MM]/[DD] [HH]-[MI]-[SS] format 'WRFdatetime': [Y], [Y], [Y], [Y], '-', [M], [M], '-', [D], [D], '_', [H], [H], ':', [M], [M], ':', [S], [S] >>> datetimeStr_conversion('1976-02-17_08:32:05','Y-m-d_H:M:S','matYmdHMS') [1976 2 17 8 32 5] >>> datetimeStr_conversion(str(137880)+',minutes since 1979-12-01_00:00:00','cfTime','Y/m/d H-M-S') 1980/03/05 18-00-00 """ import datetime as dt fname = 'datetimeStr_conversion' if StringDT[0:1] == 'h': print fname + '_____________________________________________________________' print datetimeStr_conversion.__doc__ quit() if typeSi == 'cfTime': timeval = np.float(StringDT.split(',')[0]) tunits = StringDT.split(',')[1].split(' ')[0] Srefdate = StringDT.split(',')[1].split(' ')[2] # Does reference date contain a time value [YYYY]-[MM]-[DD] [HH]:[MI]:[SS] ## yrref=Srefdate[0:4] monref=Srefdate[5:7] dayref=Srefdate[8:10] trefT = Srefdate.find(':') if not trefT == -1: # print ' ' + fname + ': refdate with time!' horref=Srefdate[11:13] minref=Srefdate[14:16] secref=Srefdate[17:19] refdate = datetimeStr_datetime( yrref + '-' + monref + '-' + dayref + \ '_' + horref + ':' + minref + ':' + secref) else: refdate = datetimeStr_datetime( yrref + '-' + monref + '-' + dayref + \ '_00:00:00') if tunits == 'weeks': newdate = refdate + dt.timedelta(weeks=float(timeval)) elif tunits == 'days': newdate = refdate + dt.timedelta(days=float(timeval)) elif tunits == 'hours': newdate = refdate + dt.timedelta(hours=float(timeval)) elif tunits == 'minutes': newdate = refdate + dt.timedelta(minutes=float(timeval)) elif tunits == 'seconds': newdate = refdate + dt.timedelta(seconds=float(timeval)) elif tunits == 'milliseconds': newdate = refdate + dt.timedelta(milliseconds=float(timeval)) else: print errormsg print ' timeref_datetime: time units "' + tunits + '" not ready!!!!' quit(-1) yr = newdate.year mo = newdate.month da = newdate.day ho = newdate.hour mi = newdate.minute se = newdate.second elif typeSi == 'matYmdHMS': yr = StringDT[0] mo = StringDT[1] da = StringDT[2] ho = StringDT[3] mi = StringDT[4] se = StringDT[5] elif typeSi == 'YmdHMS': yr = int(StringDT[0:4]) mo = int(StringDT[4:6]) da = int(StringDT[6:8]) ho = int(StringDT[8:10]) mi = int(StringDT[10:12]) se = int(StringDT[12:14]) elif typeSi == 'Y-m-d_H:M:S': dateDT = StringDT.split('_') dateD = dateDT[0].split('-') timeT = dateDT[1].split(':') yr = int(dateD[0]) mo = int(dateD[1]) da = int(dateD[2]) ho = int(timeT[0]) mi = int(timeT[1]) se = int(timeT[2]) elif typeSi == 'Y-m-d H:M:S': dateDT = StringDT.split(' ') dateD = dateDT[0].split('-') timeT = dateDT[1].split(':') yr = int(dateD[0]) mo = int(dateD[1]) da = int(dateD[2]) ho = int(timeT[0]) mi = int(timeT[1]) se = int(timeT[2]) elif typeSi == 'Y/m/d H-M-S': dateDT = StringDT.split(' ') dateD = dateDT[0].split('/') timeT = dateDT[1].split('-') yr = int(dateD[0]) mo = int(dateD[1]) da = int(dateD[2]) ho = int(timeT[0]) mi = int(timeT[1]) se = int(timeT[2]) elif typeSi == 'WRFdatetime': yr = int(StringDT[0])*1000 + int(StringDT[1])*100 + int(StringDT[2])*10 + \ int(StringDT[3]) mo = int(StringDT[5])*10 + int(StringDT[6]) da = int(StringDT[8])*10 + int(StringDT[9]) ho = int(StringDT[11])*10 + int(StringDT[12]) mi = int(StringDT[14])*10 + int(StringDT[15]) se = int(StringDT[17])*10 + int(StringDT[18]) else: print errormsg print ' ' + fname + ': type of String input date "' + typeSi + \ '" not ready !!!!' quit(-1) if typeSo == 'matYmdHMS': dateYmdHMS = np.zeros((6), dtype=int) dateYmdHMS[0] = yr dateYmdHMS[1] = mo dateYmdHMS[2] = da dateYmdHMS[3] = ho dateYmdHMS[4] = mi dateYmdHMS[5] = se elif typeSo == 'YmdHMS': dateYmdHMS = str(yr).zfill(4) + str(mo).zfill(2) + str(da).zfill(2) + \ str(ho).zfill(2) + str(mi).zfill(2) + str(se).zfill(2) elif typeSo == 'Y-m-d_H:M:S': dateYmdHMS = str(yr).zfill(4) + '-' + str(mo).zfill(2) + '-' + \ str(da).zfill(2) + '_' + str(ho).zfill(2) + ':' + str(mi).zfill(2) + ':' + \ str(se).zfill(2) elif typeSo == 'Y-m-d H:M:S': dateYmdHMS = str(yr).zfill(4) + '-' + str(mo).zfill(2) + '-' + \ str(da).zfill(2) + ' ' + str(ho).zfill(2) + ':' + str(mi).zfill(2) + ':' + \ str(se).zfill(2) elif typeSo == 'Y/m/d H-M-S': dateYmdHMS = str(yr).zfill(4) + '/' + str(mo).zfill(2) + '/' + \ str(da).zfill(2) + ' ' + str(ho).zfill(2) + '-' + str(mi).zfill(2) + '-' + \ str(se).zfill(2) elif typeSo == 'WRFdatetime': dateYmdHMS = [] yM = yr/1000 yC = (yr-yM*1000)/100 yD = (yr-yM*1000-yC*100)/10 yU = yr-yM*1000-yC*100-yD*10 mD = mo/10 mU = mo-mD*10 dD = da/10 dU = da-dD*10 hD = ho/10 hU = ho-hD*10 miD = mi/10 miU = mi-miD*10 sD = se/10 sU = se-sD*10 dateYmdHMS.append(str(yM)) dateYmdHMS.append(str(yC)) dateYmdHMS.append(str(yD)) dateYmdHMS.append(str(yU)) dateYmdHMS.append('-') dateYmdHMS.append(str(mD)) dateYmdHMS.append(str(mU)) dateYmdHMS.append('-') dateYmdHMS.append(str(dD)) dateYmdHMS.append(str(dU)) dateYmdHMS.append('_') dateYmdHMS.append(str(hD)) dateYmdHMS.append(str(hU)) dateYmdHMS.append(':') dateYmdHMS.append(str(miD)) dateYmdHMS.append(str(miU)) dateYmdHMS.append(':') dateYmdHMS.append(str(sD)) dateYmdHMS.append(str(sU)) else: print errormsg print ' ' + fname + ': type of output date "' + typeSo + '" not ready !!!!' quit(-1) return dateYmdHMS def percendone(nvals,tot,percen,msg): """ Function to provide the percentage of an action across the matrix nvals=number of values tot=total number of values percen=percentage frequency for which the message is wanted msg= message """ from sys import stdout num = int(tot * percen/100) if (nvals%num == 0): print '\r ' + msg + '{0:8.3g}'.format(nvals*100./tot) + ' %', stdout.flush() return '' def netCDFdatetime_realdatetime(units, tcalendar, times): """ Function to transfrom from netCDF CF-compilant times to real time """ import datetime as dt txtunits = units.split(' ') tunits = txtunits[0] Srefdate = txtunits[len(txtunits) - 1] # Calendar type ## is360 = False if tcalendar is not None: print ' netCDFdatetime_realdatetime: There is a calendar attribute' if tcalendar == '365_day' or tcalendar == 'noleap': print ' netCDFdatetime_realdatetime: No leap years!' isleapcal = False elif tcalendar == 'proleptic_gregorian' or tcalendar == 'standard' or tcalendar == 'gregorian': isleapcal = True elif tcalendar == '360_day': is360 = True isleapcal = False else: print errormsg print ' netCDFdatetime_realdatetime: Calendar "' + tcalendar + '" not prepared!' quit(-1) # Does reference date contain a time value [YYYY]-[MM]-[DD] [HH]:[MI]:[SS] ## timeval = Srefdate.find(':') if not timeval == -1: print ' netCDFdatetime_realdatetime: refdate with time!' refdate = datetimeStr_datetime(Srefdate) else: refdate = dateStr_date(Srefdate + '_00:00:00') dimt = len(times) # datetype = type(dt.datetime(1972,02,01)) # realdates = np.array(dimt, datetype) # print realdates ## Not in timedelta # if tunits == 'years': # for it in range(dimt): # realdate = refdate + dt.timedelta(years=float(times[it])) # realdates[it] = int(realdate.year) # elif tunits == 'months': # for it in range(dimt): # realdate = refdate + dt.timedelta(months=float(times[it])) # realdates[it] = int(realdate.year) # realdates = [] realdates = np.zeros((dimt, 6), dtype=int) if tunits == 'weeks': for it in range(dimt): realdate = refdate + dt.timedelta(weeks=float(times[it])) realdates[it,:]=[realdate.year, realdate.month, realdate.day, realdate.hour, realdate.minute, realdate.second] elif tunits == 'days': for it in range(dimt): realdate = refdate + dt.timedelta(days=float(times[it])) realdates[it,:]=[realdate.year, realdate.month, realdate.day, realdate.hour, realdate.minute, realdate.second] elif tunits == 'hours': for it in range(dimt): realdate = refdate + dt.timedelta(hours=float(times[it])) # if not isleapcal: # Nleapdays = cal.leapdays(int(refdate.year), int(realdate.year)) # realdate = realdate - dt.timedelta(days=Nleapdays) # if is360: # Nyears360 = int(realdate.year) - int(refdate.year) + 1 # realdate = realdate -dt.timedelta(days=Nyears360*5) # realdates[it] = realdate # realdates = refdate + dt.timedelta(hours=float(times)) realdates[it,:]=[realdate.year, realdate.month, realdate.day, realdate.hour, realdate.minute, realdate.second] elif tunits == 'minutes': for it in range(dimt): realdate = refdate + dt.timedelta(minutes=float(times[it])) realdates[it,:]=[realdate.year, realdate.month, realdate.day, realdate.hour, realdate.minute, realdate.second] elif tunits == 'seconds': for it in range(dimt): realdate = refdate + dt.timedelta(seconds=float(times[it])) realdates[it,:]=[realdate.year, realdate.month, realdate.day, realdate.hour, realdate.minute, realdate.second] elif tunits == 'milliseconds': for it in range(dimt): realdate = refdate + dt.timedelta(milliseconds=float(times[it])) realdates[it,:]=[realdate.year, realdate.month, realdate.day, realdate.hour, realdate.minute, realdate.second] elif tunits == 'microseconds': for it in range(dimt): realdate = refdate + dt.timedelta(microseconds=float(times[it])) realdates[it,:]=[realdate.year, realdate.month, realdate.day, realdate.hour, realdate.minute, realdate.second] else: print errormsg print ' netCDFdatetime_realdatetime: time units "' + tunits + '" is not ready!!!' quit(-1) return realdates def file_nlines(filen): """ Function to provide the number of lines of a file filen= name of the file >>> file_nlines('trajectory.dat') 49 """ fname = 'file_nlines' if not os.path.isfile(filen): print errormsg print ' ' + fname + ' file: "' + filen + '" does not exist !!' quit(-1) fo = open(filen,'r') nlines=0 for line in fo: nlines = nlines + 1 fo.close() return nlines def realdatetime1_CFcompilant(time, Srefdate, tunits): """ Function to transform a matrix with a real time value ([year, month, day, hour, minute, second]) to a netCDF one time= matrix with time Srefdate= reference date ([YYYY][MM][DD][HH][MI][SS] format) tunits= units of time respect to Srefdate >>> realdatetime1_CFcompilant([1976, 2, 17, 8, 20, 0], '19491201000000', 'hours') 229784.33333333 """ import datetime as dt yrref=int(Srefdate[0:4]) monref=int(Srefdate[4:6]) dayref=int(Srefdate[6:8]) horref=int(Srefdate[8:10]) minref=int(Srefdate[10:12]) secref=int(Srefdate[12:14]) refdate=dt.datetime(yrref, monref, dayref, horref, minref, secref) if tunits == 'weeks': cfdate = dt.datetime(time[0],time[1],time[2],time[3],time[4],time[5])-refdate cfdates = (cfdate.days + cfdate.seconds/(3600.*24.))/7. elif tunits == 'days': cfdate = dt.datetime(time[0],time[1],time[2],time[3],time[4],time[5]) - refdate cfdates = cfdate.days + cfdate.seconds/(3600.*24.) elif tunits == 'hours': cfdate = dt.datetime(time[0],time[1],time[2],time[3],time[4],time[5]) - refdate cfdates = cfdate.days*24. + cfdate.seconds/3600. elif tunits == 'minutes': cfdate = dt.datetime(time[0],time[1],time[2],time[3],time[4],time[5]) - refdate cfdates = cfdate.days*24.*60. + cfdate.seconds/60. elif tunits == 'seconds': cfdate = dt.datetime(time[0],time[1],time[2],time[3],time[4],time[5]) - refdate cfdates = cfdate.days*24.*3600. + cfdate.seconds elif tunits == 'milliseconds': cfdate = dt.datetime(time[0],time[1],time[2],time[3],time[4],time[5]) - refdate cfdates = cfdate.days*1000.*24.*3600. + cfdate.seconds*1000. elif tunits == 'microseconds': cfdate = dt.datetime(time[0],time[1],time[2],time[3],time[4],times[5]) - refdate cfdates = cfdate.days*1000000.*24.*3600. + cfdate.seconds*1000000. else: print errormsg print ' ' + fname + ': time units "' + tunits + '" is not ready!!!' quit(-1) return cfdates def basicvardef(varobj, vstname, vlname, vunits): """ Function to give the basic attributes to a variable varobj= netCDF variable object vstname= standard name of the variable vlname= long name of the variable vunits= units of the variable """ attr = varobj.setncattr('standard_name', vstname) attr = varobj.setncattr('long_name', vlname) attr = varobj.setncattr('units', vunits) return def variables_values(varName): """ Function to provide values to plot the different variables values from ASCII file 'variables_values.dat' variables_values(varName) [varName]= name of the variable return: [var name], [std name], [minimum], [maximum], [long name]('|' for spaces), [units], [color palette] (following: http://matplotlib.org/1.3.1/examples/color/colormaps_reference.html) [varn]: original name of the variable NOTE: It might be better doing it with an external ASII file. But then we got an extra dependency... >>> variables_values('WRFght') ['z', 'geopotential_height', 0.0, 80000.0, 'geopotential|height', 'm2s-2', 'rainbow'] """ import subprocess as sub fname='variables_values' if varName == 'h': print fname + '_____________________________________________________________' print variables_values.__doc__ quit() # This does not work.... # folderins = sub.Popen(["pwd"], stdout=sub.PIPE) # folder = list(folderins.communicate())[0].replace('\n','') # From http://stackoverflow.com/questions/4934806/how-can-i-find-scripts-directory-with-python folder = os.path.dirname(os.path.realpath(__file__)) infile = folder + '/variables_values.dat' if not os.path.isfile(infile): print errormsg print ' ' + fname + ": File '" + infile + "' does not exist !!" quit(-1) # Variable name might come with a statistical surname... stats=['min','max','mean','stdv', 'sum'] # Variables with a statistical section on their name... NOstatsvars = ['zmaxth', 'zmax_th', 'lmax_th', 'lmaxth'] ifst = False if not searchInlist(NOstatsvars, varName.lower()): for st in stats: if varName.find(st) > -1: print ' '+ fname + ": varibale '" + varName + "' with a " + \ "statistical surname: '",st,"' !!" Lst = len(st) LvarName = len(varName) varn = varName[0:LvarName - Lst] ifst = True break if not ifst: varn = varName ncf = open(infile, 'r') for line in ncf: if line[0:1] != '#': values = line.replace('\n','').split(',') if len(values) != 10: print errormsg print ' ' + fname + ": problem in varibale: '", values[0], \ "' it should have 10 values and it has:", len(values) quit(-1) if varn[0:6] == 'varDIM': # Variable from a dimension (all with 'varDIM' prefix) Lvarn = len(varn) varvals = [varn[6:Lvarn+1], varn[6:Lvarn+1], 0., 1., \ "variable|from|size|of|dimension|'" + varn[6:Lvarn+1] + "'", '1', \ 'rainbow'] else: varvals = [values[1].replace(' ',''), values[2].replace(' ',''), \ np.float(values[3]), np.float(values[4]),values[5].replace(' ',''),\ values[6].replace(' ',''), values[7].replace(' ','')] if values[0] == varn: ncf.close() return varvals break print errormsg print ' ' + fname + ": variable '" + varn + "' not defined !!!" ncf.close() quit(-1) return def variables_values_old(varName): """ Function to provide values to plot the different variables variables_values(varName) [varName]= name of the variable return: [var name], [std name], [minimum], [maximum], [long name]('|' for spaces), [units], [color palette] (following: http://matplotlib.org/1.3.1/examples/color/colormaps_reference.html) [varn]: original name of the variable NOTE: It might be better doing it with an external ASII file. But then we got an extra dependency... >>> variables_values('WRFght') ['z', 'geopotential_height', 0.0, 80000.0, 'geopotential|height', 'm2s-2', 'rainbow'] """ fname='variables_values' if varName == 'h': print fname + '_____________________________________________________________' print variables_values.__doc__ quit() # Variable name might come with a statistical surname... stats=['min','max','mean','stdv', 'sum'] ifst = False for st in stats: if varName.find(st) > -1: print ' '+ fname + ": varibale '" + varName + "' with a statistical "+\ " surname: '",st,"' !!" Lst = len(st) LvarName = len(varName) varn = varName[0:LvarName - Lst] ifst = True break if not ifst: varn = varName if varn[0:6] == 'varDIM': # Variable from a dimension (all with 'varDIM' prefix) Lvarn = len(varn) varvals = [varn[6:Lvarn+1], varn[6:Lvarn+1], 0., 1., \ "variable|from|size|of|dimension|'" + varn[6:Lvarn+1] + "'", '1', 'rainbox'] elif varn == 'a_tht' or varn == 'LA_THT': varvals = ['ath', 'total_thermal_plume_cover', 0., 1., \ 'total|column|thermal|plume|cover', '1', 'YlGnBu'] elif varn == 'acprc' or varn == 'RAINC': varvals = ['acprc', 'accumulated_cmulus_precipitation', 0., 3.e4, \ 'accumulated|cmulus|precipitation', 'mm', 'Blues'] elif varn == 'acprnc' or varn == 'RAINNC': varvals = ['acprnc', 'accumulated_non-cmulus_precipitation', 0., 3.e4, \ 'accumulated|non-cmulus|precipitation', 'mm', 'Blues'] elif varn == 'bils' or varn == 'LBILS': varvals = ['bils', 'surface_total_heat_flux', -100., 100., \ 'surface|total|heat|flux', 'Wm-2', 'seismic'] elif varn == 'landcat' or varn == 'category': varvals = ['landcat', 'land_categories', 0., 22., 'land|categories', '1', \ 'rainbow'] elif varn == 'c' or varn == 'QCLOUD' or varn == 'oliq' or varn == 'OLIQ': varvals = ['c', 'condensed_water_mixing_ratio', 0., 3.e-4, \ 'condensed|water|mixing|ratio', 'kgkg-1', 'BuPu'] elif varn == 'ci' or varn == 'iwcon' or varn == 'LIWCON': varvals = ['ci', 'cloud_iced_water_mixing_ratio', 0., 0.0003, \ 'cloud|iced|water|mixing|ratio', 'kgkg-1', 'Purples'] elif varn == 'cl' or varn == 'lwcon' or varn == 'LLWCON': varvals = ['cl', 'cloud_liquidwater_mixing_ratio', 0., 0.0003, \ 'cloud|liquid|water|mixing|ratio', 'kgkg-1', 'Blues'] elif varn == 'cld' or varn == 'CLDFRA' or varn == 'rneb' or varn == 'lrneb' or \ varn == 'LRNEB': varvals = ['cld', 'cloud_area_fraction', 0., 1., 'cloud|fraction', '1', \ 'gist_gray'] elif varn == 'cldc' or varn == 'rnebcon' or varn == 'lrnebcon' or \ varn == 'LRNEBCON': varvals = ['cldc', 'convective_cloud_area_fraction', 0., 1., \ 'convective|cloud|fraction', '1', 'gist_gray'] elif varn == 'cldl' or varn == 'rnebls' or varn == 'lrnebls' or varn == 'LRNEBLS': varvals = ['cldl', 'large_scale_cloud_area_fraction', 0., 1., \ 'large|scale|cloud|fraction', '1', 'gist_gray'] elif varn == 'clt' or varn == 'CLT' or varn == 'cldt' or \ varn == 'Total cloudiness': varvals = ['clt', 'cloud_area_fraction', 0., 1., 'total|cloud|cover', '1', \ 'gist_gray'] elif varn == 'cll' or varn == 'cldl' or varn == 'LCLDL' or \ varn == 'Low-level cloudiness': varvals = ['cll', 'low_level_cloud_area_fraction', 0., 1., \ 'low|level|(p|>|680|hPa)|cloud|fraction', '1', 'gist_gray'] elif varn == 'clm' or varn == 'cldm' or varn == 'LCLDM' or \ varn == 'Mid-level cloudiness': varvals = ['clm', 'mid_level_cloud_area_fraction', 0., 1., \ 'medium|level|(440|<|p|<|680|hPa)|cloud|fraction', '1', 'gist_gray'] elif varn == 'clh' or varn == 'cldh' or varn == 'LCLDH' or \ varn == 'High-level cloudiness': varvals = ['clh', 'high_level_cloud_area_fraction', 0., 1., \ 'high|level|(p|<|440|hPa)|cloud|fraction', '1', 'gist_gray'] elif varn == 'clmf' or varn == 'fbase' or varn == 'LFBASE': varvals = ['clmf', 'cloud_base_max_flux', -0.3, 0.3, 'cloud|base|max|flux', \ 'kgm-2s-1', 'seismic'] elif varn == 'clp' or varn == 'pbase' or varn == 'LPBASE': varvals = ['clp', 'cloud_base_pressure', -0.3, 0.3, 'cloud|base|pressure', \ 'Pa', 'Reds'] elif varn == 'cpt' or varn == 'ptconv' or varn == 'LPTCONV': varvals = ['cpt', 'convective_point', 0., 1., 'convective|point', '1', \ 'seismic'] elif varn == 'dqajs' or varn == 'LDQAJS': varvals = ['dqajs', 'dry_adjustment_water_vapor_tendency', -0.0003, 0.0003, \ 'dry|adjustment|water|vapor|tendency', 'kg/kg/s', 'seismic'] elif varn == 'dqcon' or varn == 'LDQCON': varvals = ['dqcon', 'convective_water_vapor_tendency', -3e-8, 3.e-8, \ 'convective|water|vapor|tendency', 'kg/kg/s', 'seismic'] elif varn == 'dqdyn' or varn == 'LDQDYN': varvals = ['dqdyn', 'dynamics_water_vapor_tendency', -3.e-7, 3.e-7, \ 'dynamics|water|vapor|tendency', 'kg/kg/s', 'seismic'] elif varn == 'dqeva' or varn == 'LDQEVA': varvals = ['dqeva', 'evaporation_water_vapor_tendency', -3.e-6, 3.e-6, \ 'evaporation|water|vapor|tendency', 'kg/kg/s', 'seismic'] elif varn == 'dqlscst' or varn == 'LDQLSCST': varvals = ['dqlscst', 'stratocumulus_water_vapor_tendency', -3.e-7, 3.e-7, \ 'stratocumulus|water|vapor|tendency', 'kg/kg/s', 'seismic'] elif varn == 'dqlscth' or varn == 'LDQLSCTH': varvals = ['dqlscth', 'thermals_water_vapor_tendency', -3.e-7, 3.e-7, \ 'thermal|plumes|water|vapor|tendency', 'kg/kg/s', 'seismic'] elif varn == 'dqlsc' or varn == 'LDQLSC': varvals = ['dqlsc', 'condensation_water_vapor_tendency', -3.e-6, 3.e-6, \ 'condensation|water|vapor|tendency', 'kg/kg/s', 'seismic'] elif varn == 'dqphy' or varn == 'LDQPHY': varvals = ['dqphy', 'physics_water_vapor_tendency', -3.e-7, 3.e-7, \ 'physics|water|vapor|tendency', 'kg/kg/s', 'seismic'] elif varn == 'dqthe' or varn == 'LDQTHE': varvals = ['dqthe', 'thermals_water_vapor_tendency', -3.e-7, 3.e-7, \ 'thermal|plumes|water|vapor|tendency', 'kg/kg/s', 'seismic'] elif varn == 'dqvdf' or varn == 'LDQVDF': varvals = ['dqvdf', 'vertical_difussion_water_vapor_tendency', -3.e-8, 3.e-8,\ 'vertical|difussion|water|vapor|tendency', 'kg/kg/s', 'seismic'] elif varn == 'dqwak' or varn == 'LDQWAK': varvals = ['dqwak', 'wake_water_vapor_tendency', -3.e-7, 3.e-7, \ 'wake|water|vapor|tendency', 'kg/kg/s', 'seismic'] elif varn == 'dta' or varn == 'tnt' or varn == 'LTNT': varvals = ['dta', 'tendency_air_temperature', -3.e-3, 3.e-3, \ 'tendency|of|air|temperature', 'K/s', 'seismic'] elif varn == 'dtac' or varn == 'tntc' or varn == 'LTNTC': varvals = ['dtac', 'moist_convection_tendency_air_temperature', -3.e-3, \ 3.e-3, 'moist|convection|tendency|of|air|temperature', 'K/s', 'seismic'] elif varn == 'dtar' or varn == 'tntr' or varn == 'LTNTR': varvals = ['dtar', 'radiative_heating_tendency_air_temperature', -3.e-3, \ 3.e-3, 'radiative|heating|tendency|of|air|temperature', 'K/s', 'seismic'] elif varn == 'dtascpbl' or varn == 'tntscpbl' or varn == 'LTNTSCPBL': varvals = ['dtascpbl', \ 'stratiform_cloud_precipitation_BL_mixing_tendency_air_temperature', \ -3.e-6, 3.e-6, \ 'stratiform|cloud|precipitation|Boundary|Layer|mixing|tendency|air|' + 'temperature', 'K/s', 'seismic'] elif varn == 'dtajs' or varn == 'LDTAJS': varvals = ['dtajs', 'dry_adjustment_thermal_tendency', -3.e-5, 3.e-5, \ 'dry|adjustment|thermal|tendency', 'K/s', 'seismic'] elif varn == 'dtcon' or varn == 'LDTCON': varvals = ['dtcon', 'convective_thermal_tendency', -3.e-5, 3.e-5, \ 'convective|thermal|tendency', 'K/s', 'seismic'] elif varn == 'dtdyn' or varn == 'LDTDYN': varvals = ['dtdyn', 'dynamics_thermal_tendency', -3.e-4, 3.e-4, \ 'dynamics|thermal|tendency', 'K/s', 'seismic'] elif varn == 'dteva' or varn == 'LDTEVA': varvals = ['dteva', 'evaporation_thermal_tendency', -3.e-3, 3.e-3, \ 'evaporation|thermal|tendency', 'K/s', 'seismic'] elif varn == 'dtlscst' or varn == 'LDTLSCST': varvals = ['dtlscst', 'stratocumulus_thermal_tendency', -3.e-4, 3.e-4, \ 'stratocumulus|thermal|tendency', 'K/s', 'seismic'] elif varn == 'dtlscth' or varn == 'LDTLSCTH': varvals = ['dtlscth', 'thermals_thermal_tendency', -3.e-4, 3.e-4, \ 'thermal|plumes|thermal|tendency', 'K/s', 'seismic'] elif varn == 'dtlsc' or varn == 'LDTLSC': varvals = ['dtlsc', 'condensation_thermal_tendency', -3.e-3, 3.e-3, \ 'condensation|thermal|tendency', 'K/s', 'seismic'] elif varn == 'dtlwr' or varn == 'LDTLWR': varvals = ['dtlwr', 'long_wave_thermal_tendency', -3.e-3, 3.e-3, \ 'long|wave|radiation|thermal|tendency', 'K/s', 'seismic'] elif varn == 'dtphy' or varn == 'LDTPHY': varvals = ['dtphy', 'physics_thermal_tendency', -3.e-4, 3.e-4, \ 'physics|thermal|tendency', 'K/s', 'seismic'] elif varn == 'dtsw0' or varn == 'LDTSW0': varvals = ['dtsw0', 'cloudy_sky_short_wave_thermal_tendency', -3.e-4, 3.e-4, \ 'cloudy|sky|short|wave|radiation|thermal|tendency', 'K/s', 'seismic'] elif varn == 'dtthe' or varn == 'LDTTHE': varvals = ['dtthe', 'thermals_thermal_tendency', -3.e-4, 3.e-4, \ 'thermal|plumes|thermal|tendency', 'K/s', 'seismic'] elif varn == 'dtvdf' or varn == 'LDTVDF': varvals = ['dtvdf', 'vertical_difussion_thermal_tendency', -3.e-5, 3.e-5, \ 'vertical|difussion|thermal|tendency', 'K/s', 'seismic'] elif varn == 'dtwak' or varn == 'LDTWAK': varvals = ['dtwak', 'wake_thermal_tendency', -3.e-4, 3.e-4, \ 'wake|thermal|tendency', 'K/s', 'seismic'] elif varn == 'ducon' or varn == 'LDUCON': varvals = ['ducon', 'convective_eastward_wind_tendency', -3.e-3, 3.e-3, \ 'convective|eastward|wind|tendency', 'ms-2', 'seismic'] elif varn == 'dudyn' or varn == 'LDUDYN': varvals = ['dudyn', 'dynamics_eastward_wind_tendency', -3.e-3, 3.e-3, \ 'dynamics|eastward|wind|tendency', 'ms-2', 'seismic'] elif varn == 'duvdf' or varn == 'LDUVDF': varvals = ['duvdf', 'vertical_difussion_eastward_wind_tendency', -3.e-3, \ 3.e-3, 'vertical|difussion|eastward|wind|tendency', 'ms-2', 'seismic'] elif varn == 'dvcon' or varn == 'LDVCON': varvals = ['dvcon', 'convective_difussion_northward_wind_tendency', -3.e-3, \ 3.e-3, 'convective|northward|wind|tendency', 'ms-2', 'seismic'] elif varn == 'dvdyn' or varn == 'LDVDYN': varvals = ['dvdyn', 'dynamics_northward_wind_tendency', -3.e-3, \ 3.e-3, 'dynamics|difussion|northward|wind|tendency', 'ms-2', 'seismic'] elif varn == 'dvvdf' or varn == 'LDVVDF': varvals = ['dvvdf', 'vertical_difussion_northward_wind_tendency', -3.e-3, \ 3.e-3, 'vertical|difussion|northward|wind|tendency', 'ms-2', 'seismic'] elif varn == 'etau' or varn == 'ZNU': varvals = ['etau', 'etau', 0., 1, 'eta values on half (mass) levels', '-', \ 'reds'] elif varn == 'evspsbl' or varn == 'LEVAP' or varn == 'evap' or varn == 'SFCEVPde': varvals = ['evspsbl', 'water_evaporation_flux', 0., 1.5e-4, \ 'water|evaporation|flux', 'kgm-2s-1', 'Blues'] elif varn == 'evspsbl' or varn == 'SFCEVPde': varvals = ['evspsblac', 'water_evaporation_flux_ac', 0., 1.5e-4, \ 'accumulated|water|evaporation|flux', 'kgm-2', 'Blues'] elif varn == 'g' or varn == 'QGRAUPEL': varvals = ['g', 'grauepl_mixing_ratio', 0., 0.0003, 'graupel|mixing|ratio', \ 'kgkg-1', 'Purples'] elif varn == 'h2o' or varn == 'LH2O': varvals = ['h2o', 'water_mass_fraction', 0., 3.e-2, \ 'mass|fraction|of|water', '1', 'Blues'] elif varn == 'h' or varn == 'QHAIL': varvals = ['h', 'hail_mixing_ratio', 0., 0.0003, 'hail|mixing|ratio', \ 'kgkg-1', 'Purples'] elif varn == 'hfls' or varn == 'LH' or varn == 'LFLAT' or varn == 'flat': varvals = ['hfls', 'surface_upward_latent_heat_flux', -400., 400., \ 'upward|latnt|heat|flux|at|the|surface', 'Wm-2', 'seismic'] elif varn == 'hfss' or varn == 'LSENS' or varn == 'sens' or varn == 'HFX': varvals = ['hfss', 'surface_upward_sensible_heat_flux', -150., 150., \ 'upward|sensible|heat|flux|at|the|surface', 'Wm-2', 'seismic'] elif varn == 'hfso' or varn == 'GRDFLX': varvals = ['hfso', 'downward_heat_flux_in_soil', -150., 150., \ 'Downward|soil|heat|flux', 'Wm-2', 'seismic'] elif varn == 'hus' or varn == 'WRFrh' or varn == 'LMDZrh' or varn == 'rhum' or \ varn == 'LRHUM': varvals = ['hus', 'specific_humidity', 0., 1., 'specific|humidty', '1', \ 'BuPu'] elif varn == 'huss' or varn == 'WRFrhs' or varn == 'LMDZrhs' or varn == 'rh2m' or\ varn == 'LRH2M': varvals = ['huss', 'specific_humidity', 0., 1., 'specific|humidty|at|2m', \ '1', 'BuPu'] elif varn == 'i' or varn == 'QICE': varvals = ['i', 'iced_water_mixing_ratio', 0., 0.0003, \ 'iced|water|mixing|ratio', 'kgkg-1', 'Purples'] elif varn == 'lat' or varn == 'XLAT' or varn == 'XLAT_M' or varn == 'latitude': varvals = ['lat', 'latitude', -90., 90., 'latitude', 'degrees North', \ 'seismic'] elif varn == 'lcl' or varn == 's_lcl' or varn == 'ls_lcl' or varn == 'LS_LCL': varvals = ['lcl', 'condensation_level', 0., 2500., 'level|of|condensation', \ 'm', 'Greens'] elif varn == 'lambdath' or varn == 'lambda_th' or varn == 'LLAMBDA_TH': varvals = ['lambdath', 'thermal_plume_vertical_velocity', -30., 30., \ 'thermal|plume|vertical|velocity', 'm/s', 'seismic'] elif varn == 'lmaxth' or varn == 'LLMAXTH': varvals = ['lmaxth', 'upper_level_thermals', 0., 100., 'upper|level|thermals'\ , '1', 'Greens'] elif varn == 'lon' or varn == 'XLONG' or varn == 'XLONG_M': varvals = ['lon', 'longitude', -180., 180., 'longitude', 'degrees East', \ 'seismic'] elif varn == 'longitude': varvals = ['lon', 'longitude', 0., 360., 'longitude', 'degrees East', \ 'seismic'] elif varn == 'orog' or varn == 'HGT' or varn == 'HGT_M': varvals = ['orog', 'orography', 0., 3000., 'surface|altitude', 'm','terrain'] elif varn == 'pfc' or varn == 'plfc' or varn == 'LPLFC': varvals = ['pfc', 'pressure_free_convection', 100., 1100., \ 'pressure|free|convection', 'hPa', 'BuPu'] elif varn == 'plcl' or varn == 'LPLCL': varvals = ['plcl', 'pressure_lifting_condensation_level', 700., 1100., \ 'pressure|lifting|condensation|level', 'hPa', 'BuPu'] elif varn == 'pr' or varn == 'RAINTOT' or varn == 'precip' or \ varn == 'LPRECIP' or varn == 'Precip Totale liq+sol': varvals = ['pr', 'precipitation_flux', 0., 1.e-4, 'precipitation|flux', \ 'kgm-2s-1', 'BuPu'] elif varn == 'prprof' or varn == 'vprecip' or varn == 'LVPRECIP': varvals = ['prprof', 'precipitation_profile', 0., 1.e-3, \ 'precipitation|profile', 'kg/m2/s', 'BuPu'] elif varn == 'prprofci' or varn == 'pr_con_i' or varn == 'LPR_CON_I': varvals = ['prprofci', 'precipitation_profile_convective_i', 0., 1.e-3, \ 'precipitation|profile|convective|i', 'kg/m2/s', 'BuPu'] elif varn == 'prprofcl' or varn == 'pr_con_l' or varn == 'LPR_CON_L': varvals = ['prprofcl', 'precipitation_profile_convective_l', 0., 1.e-3, \ 'precipitation|profile|convective|l', 'kg/m2/s', 'BuPu'] elif varn == 'prprofli' or varn == 'pr_lsc_i' or varn == 'LPR_LSC_I': varvals = ['prprofli', 'precipitation_profile_large_scale_i', 0., 1.e-3, \ 'precipitation|profile|large|scale|i', 'kg/m2/s', 'BuPu'] elif varn == 'prprofll' or varn == 'pr_lsc_l' or varn == 'LPR_LSC_L': varvals = ['prprofll', 'precipitation_profile_large_scale_l', 0., 1.e-3, \ 'precipitation|profile|large|scale|l', 'kg/m2/s', 'BuPu'] elif varn == 'pracc' or varn == 'ACRAINTOT': varvals = ['pracc', 'precipitation_amount', 0., 100., \ 'accumulated|precipitation', 'kgm-2', 'BuPu'] elif varn == 'prc' or varn == 'LPLUC' or varn == 'pluc' or varn == 'WRFprc' or \ varn == 'RAINCde': varvals = ['prc', 'convective_precipitation_flux', 0., 2.e-4, \ 'convective|precipitation|flux', 'kgm-2s-1', 'Blues'] elif varn == 'prci' or varn == 'pr_con_i' or varn == 'LPR_CON_I': varvals = ['prci', 'convective_ice_precipitation_flux', 0., 0.003, \ 'convective|ice|precipitation|flux', 'kgm-2s-1', 'Purples'] elif varn == 'prcl' or varn == 'pr_con_l' or varn == 'LPR_CON_L': varvals = ['prcl', 'convective_liquid_precipitation_flux', 0., 0.003, \ 'convective|liquid|precipitation|flux', 'kgm-2s-1', 'Blues'] elif varn == 'pres' or varn == 'presnivs' or varn == 'pressure' or \ varn == 'lpres' or varn == 'LPRES': varvals = ['pres', 'air_pressure', 0., 103000., 'air|pressure', 'Pa', \ 'Blues'] elif varn == 'prls' or varn == 'WRFprls' or varn == 'LPLUL' or varn == 'plul' or \ varn == 'RAINNCde': varvals = ['prls', 'large_scale_precipitation_flux', 0., 2.e-4, \ 'large|scale|precipitation|flux', 'kgm-2s-1', 'Blues'] elif varn == 'prsn' or varn == 'SNOW' or varn == 'snow' or varn == 'LSNOW': varvals = ['prsn', 'snowfall', 0., 1.e-4, 'snowfall|flux', 'kgm-2s-1', 'BuPu'] elif varn == 'prw' or varn == 'WRFprh': varvals = ['prw', 'atmosphere_water_vapor_content', 0., 10., \ 'water|vapor"path', 'kgm-2', 'Blues'] elif varn == 'ps' or varn == 'psfc' or varn =='PSFC' or varn == 'psol' or \ varn == 'Surface Pressure': varvals=['ps', 'surface_air_pressure', 85000., 105400., 'surface|pressure', \ 'hPa', 'cool'] elif varn == 'psl' or varn == 'mslp' or varn =='WRFmslp': varvals=['psl', 'air_pressure_at_sea_level', 85000., 104000., \ 'mean|sea|level|pressure', 'Pa', 'Greens'] elif varn == 'qth' or varn == 'q_th' or varn == 'LQ_TH': varvals = ['qth', 'thermal_plume_total_water_content', 0., 25., \ 'total|water|cotent|in|thermal|plume', 'mm', 'YlOrRd'] elif varn == 'r' or varn == 'QVAPOR' or varn == 'ovap' or varn == 'LOVAP': varvals = ['r', 'water_mixing_ratio', 0., 0.03, 'water|mixing|ratio', \ 'kgkg-1', 'BuPu'] elif varn == 'r2' or varn == 'Q2': varvals = ['r2', 'water_mixing_ratio_at_2m', 0., 0.03, 'water|mixing|' + \ 'ratio|at|2|m','kgkg-1', 'BuPu'] elif varn == 'rsds' or varn == 'SWdnSFC' or varn == 'SWdn at surface' or \ varn == 'SWDOWN': varvals=['rsds', 'surface_downwelling_shortwave_flux_in_air', 0., 1200., \ 'downward|SW|surface|radiation', 'Wm-2' ,'Reds'] elif varn == 'rsdsacc': varvals=['rsdsacc', 'accumulated_surface_downwelling_shortwave_flux_in_air', \ 0., 1200., 'accumulated|downward|SW|surface|radiation', 'Wm-2' ,'Reds'] elif varn == 'rvor' or varn == 'WRFrvor': varvals = ['rvor', 'air_relative_vorticity', -2.5E-3, 2.5E-3, \ 'air|relative|vorticity', 's-1', 'seismic'] elif varn == 'rvors' or varn == 'WRFrvors': varvals = ['rvors', 'surface_air_relative_vorticity', -2.5E-3, 2.5E-3, \ 'surface|air|relative|vorticity', 's-1', 'seismic'] elif varn == 's' or varn == 'QSNOW': varvals = ['s', 'snow_mixing_ratio', 0., 0.0003, 'snow|mixing|ratio', \ 'kgkg-1', 'Purples'] elif varn == 'stherm' or varn == 'LS_THERM': varvals = ['stherm', 'thermals_excess', 0., 0.8, 'thermals|excess', 'K', \ 'Reds'] elif varn == 'ta' or varn == 'WRFt' or varn == 'temp' or varn == 'LTEMP' or \ varn == 'Air temperature': varvals = ['ta', 'air_temperature', 195., 320., 'air|temperature', 'K', \ 'YlOrRd'] elif varn == 'tah' or varn == 'theta' or varn == 'LTHETA': varvals = ['tah', 'potential_air_temperature', 195., 320., \ 'potential|air|temperature', 'K', 'YlOrRd'] elif varn == 'tas' or varn == 'T2' or varn == 't2m' or varn == 'T2M' or \ varn == 'Temperature 2m': varvals = ['tas', 'air_temperature', 240., 310., 'air|temperature|at|2m', ' \ K', 'YlOrRd'] elif varn == 'tds' or varn == 'TH2': varvals = ['tds', 'air_dew_point_temperature', 240., 310., \ 'air|dew|point|temperature|at|2m', 'K', 'YlGnBu'] elif varn == 'tke' or varn == 'TKE' or varn == 'tke' or varn == 'LTKE': varvals = ['tke', 'turbulent_kinetic_energy', 0., 0.003, \ 'turbulent|kinetic|energy', 'm2/s2', 'Reds'] elif varn == 'time'or varn == 'time_counter': varvals = ['time', 'time', 0., 1000., 'time', \ 'hours|since|1949/12/01|00:00:00', 'Reds'] elif varn == 'tmla' or varn == 's_pblt' or varn == 'LS_PBLT': varvals = ['tmla', 'atmosphere_top_boundary_layer_temperature', 250., 330., \ 'atmosphere|top|boundary|layer|temperature', 'K', 'Reds'] elif varn == 'ua' or varn == 'vitu' or varn == 'U' or varn == 'Zonal wind' or \ varn == 'LVITU': varvals = ['ua', 'eastward_wind', -30., 30., 'eastward|wind', 'ms-1', \ 'seismic'] elif varn == 'uas' or varn == 'u10m' or varn == 'U10' or varn =='Vent zonal 10m': varvals = ['uas', 'eastward_wind', -30., 30., 'eastward|2m|wind', \ 'ms-1', 'seismic'] elif varn == 'va' or varn == 'vitv' or varn == 'V' or varn == 'Meridional wind' \ or varn == 'LVITV': varvals = ['va', 'northward_wind', -30., 30., 'northward|wind', 'ms-1', \ 'seismic'] elif varn == 'vas' or varn == 'v10m' or varn == 'V10' or \ varn =='Vent meridien 10m': varvals = ['vas', 'northward_wind', -30., 30., 'northward|2m|wind', 'ms-1', \ 'seismic'] elif varn == 'wakedeltaq' or varn == 'wake_deltaq' or varn == 'lwake_deltaq' or \ varn == 'LWAKE_DELTAQ': varvals = ['wakedeltaq', 'wake_delta_vapor', -0.003, 0.003, \ 'wake|delta|mixing|ratio', '-', 'seismic'] elif varn == 'wakedeltat' or varn == 'wake_deltat' or varn == 'lwake_deltat' or \ varn == 'LWAKE_DELTAT': varvals = ['wakedeltat', 'wake_delta_temp', -0.003, 0.003, \ 'wake|delta|temperature', '-', 'seismic'] elif varn == 'wakeh' or varn == 'wake_h' or varn == 'LWAKE_H': varvals = ['wakeh', 'wake_height', 0., 1000., 'height|of|the|wakes', 'm', \ 'YlOrRd'] elif varn == 'wakeomg' or varn == 'wake_omg' or varn == 'lwake_omg' or \ varn == 'LWAKE_OMG': varvals = ['wakeomg', 'wake_omega', 0., 3., 'wake|omega', \ '-', 'BuGn'] elif varn == 'wakes' or varn == 'wake_s' or varn == 'LWAKE_S': varvals = ['wakes', 'wake_area_fraction', 0., 0.5, 'wake|spatial|fraction', \ '1', 'BuGn'] elif varn == 'wa' or varn == 'W' or varn == 'Vertical wind': varvals = ['wa', 'upward_wind', -10., 10., 'upward|wind', 'ms-1', \ 'seismic'] elif varn == 'wap' or varn == 'vitw' or varn == 'LVITW': varvals = ['wap', 'upward_wind', -3.e-10, 3.e-10, 'upward|wind', 'mPa-1', \ 'seismic'] elif varn == 'wss' or varn == 'SPDUV': varvals = ['wss', 'air_velocity', 0., 30., 'surface|horizontal|wind|speed', \ 'ms-1', 'Reds'] # Water budget # Water budget de-accumulated elif varn == 'ccond' or varn == 'CCOND' or varn == 'ACCCONDde': varvals = ['ccond', 'cw_cond', 0., 30., \ 'cloud|water|condensation', 'mm', 'Reds'] elif varn == 'wbr' or varn == 'ACQVAPORde': varvals = ['wbr', 'wbr', 0., 30., 'Water|Budget|water|wapor', 'mm', 'Blues'] elif varn == 'diabh' or varn == 'DIABH' or varn == 'ACDIABHde': varvals = ['diabh', 'diabh', 0., 30., 'diabatic|heating', 'K', 'Reds'] elif varn == 'wbpw' or varn == 'WBPW' or varn == 'WBACPWde': varvals = ['wbpw', 'water_budget_pw', 0., 30., 'Water|Budget|water|content',\ 'mms-1', 'Reds'] elif varn == 'wbf' or varn == 'WBACF' or varn == 'WBACFde': varvals = ['wbf', 'water_budget_hfcqv', 0., 30., \ 'Water|Budget|horizontal|convergence|of|water|vapour|(+,|' + \ 'conv.;|-,|div.)', 'mms-1', 'Reds'] elif varn == 'wbfc' or varn == 'WBFC' or varn == 'WBACFCde': varvals = ['wbfc', 'water_budget_fc', 0., 30., \ 'Water|Budget|horizontal|convergence|of|cloud|(+,|conv.;|-,|' +\ 'div.)', 'mms-1', 'Reds'] elif varn == 'wbfp' or varn == 'WBFP' or varn == 'WBACFPde': varvals = ['wbfp', 'water_budget_cfp', 0., 30., \ 'Water|Budget|horizontal|convergence|of|precipitation|(+,|' + \ 'conv.;|-,|div.)', 'mms-1', 'Reds'] elif varn == 'wbz' or varn == 'WBZ' or varn == 'WBACZde': varvals = ['wbz', 'water_budget_z', 0., 30., \ 'Water|Budget|vertical|convergence|of|water|vapour|(+,|conv.' +\ ';|-,|div.)', 'mms-1', 'Reds'] elif varn == 'wbc' or varn == 'WBC' or varn == 'WBACCde': varvals = ['wbc', 'water_budget_c', 0., 30., \ 'Water|Budget|Cloud|water|species','mms-1', 'Reds'] elif varn == 'wbqvd' or varn == 'WBQVD' or varn == 'WBACQVDde': varvals = ['wbqvd', 'water_budget_qvd', 0., 30., \ 'Water|Budget|water|vapour|divergence', 'mms-1', 'Reds'] elif varn == 'wbqvblten' or varn == 'WBQVBLTEN' or varn == 'WBACQVBLTENde': varvals = ['wbqvblten', 'water_budget_qv_blten', 0., 30., \ 'Water|Budget|QV|tendency|due|to|pbl|parameterization', \ 'kg kg-1 s-1', 'Reds'] elif varn == 'wbqvcuten' or varn == 'WBQVCUTEN' or varn == 'WBACQVCUTENde': varvals = ['wbqvcuten', 'water_budget_qv_cuten', 0., 30., \ 'Water|Budget|QV|tendency|due|to|cu|parameterization', \ 'kg kg-1 s-1', 'Reds'] elif varn == 'wbqvshten' or varn == 'WBQVSHTEN' or varn == 'WBACQVSHTENde': varvals = ['wbqvshten', 'water_budget_qv_shten', 0., 30., \ 'Water|Budget|QV|tendency|due|to|shallow|cu|parameterization', \ 'kg kg-1 s-1', 'Reds'] elif varn == 'wbpr' or varn == 'WBP' or varn == 'WBACPde': varvals = ['wbpr', 'water_budget_pr', 0., 30., \ 'Water|Budget|recipitation', 'mms-1', 'Reds'] elif varn == 'wbpw' or varn == 'WBPW' or varn == 'WBACPWde': varvals = ['wbpw', 'water_budget_pw', 0., 30., \ 'Water|Budget|water|content', 'mms-1', 'Reds'] elif varn == 'wbcondt' or varn == 'WBCONDT' or varn == 'WBACCONDTde': varvals = ['wbcondt', 'water_budget_condt', 0., 30., \ 'Water|Budget|condensation|and|deposition', 'mms-1', 'Reds'] elif varn == 'wbqcm' or varn == 'WBQCM' or varn == 'WBACQCMde': varvals = ['wbqcm', 'water_budget_qcm', 0., 30., \ 'Water|Budget|hydrometeor|change|and|convergence', 'mms-1', 'Reds'] elif varn == 'wbsi' or varn == 'WBSI' or varn == 'WBACSIde': varvals = ['wbsi', 'water_budget_si', 0., 30., \ 'Water|Budget|hydrometeor|sink', 'mms-1', 'Reds'] elif varn == 'wbso' or varn == 'WBSO' or varn == 'WBACSOde': varvals = ['wbso', 'water_budget_so', 0., 30., \ 'Water|Budget|hydrometeor|source', 'mms-1', 'Reds'] # Water Budget accumulated elif varn == 'ccondac' or varn == 'ACCCOND': varvals = ['ccondac', 'cw_cond_ac', 0., 30., \ 'accumulated|cloud|water|condensation', 'mm', 'Reds'] elif varn == 'rac' or varn == 'ACQVAPOR': varvals = ['rac', 'ac_r', 0., 30., 'accumualted|water|wapor', 'mm', 'Blues'] elif varn == 'diabhac' or varn == 'ACDIABH': varvals = ['diabhac', 'diabh_ac', 0., 30., 'accumualted|diabatic|heating', \ 'K', 'Reds'] elif varn == 'wbpwac' or varn == 'WBACPW': varvals = ['wbpwac', 'water_budget_pw_ac', 0., 30., \ 'Water|Budget|accumulated|water|content', 'mm', 'Reds'] elif varn == 'wbfac' or varn == 'WBACF': varvals = ['wbfac', 'water_budget_hfcqv_ac', 0., 30., \ 'Water|Budget|accumulated|horizontal|convergence|of|water|vapour|(+,|' + \ 'conv.;|-,|div.)', 'mm', 'Reds'] elif varn == 'wbfcac' or varn == 'WBACFC': varvals = ['wbfcac', 'water_budget_fc_ac', 0., 30., \ 'Water|Budget|accumulated|horizontal|convergence|of|cloud|(+,|conv.;|-,|' +\ 'div.)', 'mm', 'Reds'] elif varn == 'wbfpac' or varn == 'WBACFP': varvals = ['wbfpac', 'water_budget_cfp_ac', 0., 30., \ 'Water|Budget|accumulated|horizontal|convergence|of|precipitation|(+,|' + \ 'conv.;|-,|div.)', 'mm', 'Reds'] elif varn == 'wbzac' or varn == 'WBACZ': varvals = ['wbzac', 'water_budget_z_ac', 0., 30., \ 'Water|Budget|accumulated|vertical|convergence|of|water|vapour|(+,|conv.' +\ ';|-,|div.)', 'mm', 'Reds'] elif varn == 'wbcac' or varn == 'WBACC': varvals = ['wbcac', 'water_budget_c_ac', 0., 30., \ 'Water|Budget|accumulated|Cloud|water|species','mm', 'Reds'] elif varn == 'wbqvdac' or varn == 'WBACQVD': varvals = ['wbqvdac', 'water_budget_qvd_ac', 0., 30., \ 'Water|Budget|accumulated|water|vapour|divergence', 'mm', 'Reds'] elif varn == 'wbqvbltenac' or varn == 'WBACQVBLTEN': varvals = ['wbqvbltenac', 'water_budget_qv_blten_ac', 0., 30., \ 'Water|Budget|accumulated|QV|tendency|due|to|pbl|parameterization', \ 'kg kg-1 s-1', 'Reds'] elif varn == 'wbqvcutenac' or varn == 'WBACQVCUTEN': varvals = ['wbqvcutenac', 'water_budget_qv_cuten_ac', 0., 30., \ 'Water|Budget|accumulated|QV|tendency|due|to|cu|parameterization', \ 'kg kg-1 s-1', 'Reds'] elif varn == 'wbqvshtenac' or varn == 'WBACQVSHTEN': varvals = ['wbqvshtenac', 'water_budget_qv_shten_ac', 0., 30., \ 'Water|Budget|accumulated|QV|tendency|due|to|shallow|cu|parameterization', \ 'kg kg-1 s-1', 'Reds'] elif varn == 'wbprac' or varn == 'WBACP': varvals = ['wbprac', 'water_budget_pr_ac', 0., 30., \ 'Water|Budget|accumulated|precipitation', 'mm', 'Reds'] elif varn == 'wbpwac' or varn == 'WBACPW': varvals = ['wbpwac', 'water_budget_pw_ac', 0., 30., \ 'Water|Budget|accumulated|water|content', 'mm', 'Reds'] elif varn == 'wbcondtac' or varn == 'WBACCONDT': varvals = ['wbcondtac', 'water_budget_condt_ac', 0., 30., \ 'Water|Budget|accumulated|condensation|and|deposition', 'mm', 'Reds'] elif varn == 'wbqcmac' or varn == 'WBACQCM': varvals = ['wbqcmac', 'water_budget_qcm_ac', 0., 30., \ 'Water|Budget|accumulated|hydrometeor|change|and|convergence', 'mm', 'Reds'] elif varn == 'wbsiac' or varn == 'WBACSI': varvals = ['wbsiac', 'water_budget_si_ac', 0., 30., \ 'Water|Budget|accumulated|hydrometeor|sink', 'mm', 'Reds'] elif varn == 'wbsoac' or varn == 'WBACSO': varvals = ['wbsoac', 'water_budget_so_ac', 0., 30., \ 'Water|Budget|accumulated|hydrometeor|source', 'mm', 'Reds'] elif varn == 'xtime' or varn == 'XTIME': varvals = ['xtime', 'time', 0., 1.e5, 'time', \ 'minutes|since|simulation|start', 'Reds'] elif varn == 'x' or varn == 'X': varvals = ['x', 'x', 0., 100., 'x', '-', 'Reds'] elif varn == 'y' or varn == 'Y': varvals = ['y', 'y', 0., 100., 'y', '-', 'Blues'] elif varn == 'z' or varn == 'Z': varvals = ['z', 'z', 0., 100., 'z', '-', 'Greens'] elif varn == 'zg' or varn == 'WRFght' or varn == 'Geopotential height' or \ varn == 'geop' or varn == 'LGEOP': varvals = ['zg', 'geopotential_height', 0., 80000., 'geopotential|height', \ 'm2s-2', 'rainbow'] elif varn == 'zmaxth' or varn == 'zmax_th' or varn == 'LZMAX_TH': varvals = ['zmaxth', 'thermal_plume_height', 0., 4000., \ 'maximum|thermals|plume|height', 'm', 'YlOrRd'] elif varn == 'zmla' or varn == 's_pblh' or varn == 'LS_PBLH': varvals = ['zmla', 'atmosphere_boundary_layer_thickness', 0., 2500., \ 'atmosphere|boundary|layer|thickness', 'm', 'Blues'] else: print errormsg print ' ' + fname + ": variable '" + varn + "' not defined !!!" quit(-1) return varvals def lonlat2D(lon,lat): """ Function to return lon, lat 2D matrices from any lon,lat matrix lon= matrix with longitude values lat= matrix with latitude values """ fname = 'lonlat2D' if len(lon.shape) != len(lat.shape): print errormsg print ' ' + fname + ': longitude values with shape:', lon.shape, \ 'is different than latitude values with shape:', lat.shape, '(dif. size) !!' quit(-1) if len(lon.shape) == 3: lonvv = lon[0,:,:] latvv = lat[0,:,:] elif len(lon.shape) == 2: lonvv = lon[:] latvv = lat[:] elif len(lon.shape) == 1: lonlatv = np.meshgrid(lon[:],lat[:]) lonvv = lonlatv[0] latvv = lonlatv[1] return lonvv, latvv def transform(vals, trans, dxv='0', dyv='0', dxt='0', dyt='0', dxl='0', \ dyl='0', dxtit='0', dytit='0', axxkind='fixpixel', axykind='fixpixel'): """ Function to transform the values and the axes vals= values to transform trans= '|' separated list of operations of transformation 'transpose': Transpose matrix of values (x-->y, y-->x) 'flip@[x/y]': Flip the given axis d[x/y]v= original values for the [x/y]-axis d[x/y]t= original ticks for the [x/y]-axis d[x/y]l= original tick-labels for the [x/y]-axis d[x/y]tit= original titles for the [x/y]-axis ax[x/y]kind= kind of axis reference 'fixpixel': pixel preserves size all along axis 'data': pixel follows data values (as in a georeferenced map) >>> mat = np.arange(15).reshape(3,5) >>> xvals = np.zeros((3,5), dtype=np.float) >>> yvals = np.zeros((3,5), dtype=np.float) >>> for i in range(5): >>> xvals[:,i] = -1.25 + i*0.5 >>> for j in range(3): >>> yvals[j,:] = 40.25 + j*0.5 >>> xticks = np.array([-1.25, -0.25, 0.25]) >>> yticks = np.array([40.25, 41.25]) >>> xticklab = ['1.25 W', '0.25 W', '0,25 E'] >>> yticklab = ['40.25 N', '41.25 N'] >>> xtit = 'Longitude' >>> ytit = 'Latitude' >>> nv, ndxv, ndyv, ndxt, ndyt, dxl, ndyl, ndxT, ndyT = transform(mat, 'transpose', \ xvals, yvals, xticks, yticks, xticklab, yticklab, xtit, ytit) [[ 0 5 10] [ 1 6 11] [ 2 7 12] [ 3 8 13] [ 4 9 14]] [[ 40.25 40.75 41.25] [ 40.25 40.75 41.25] [ 40.25 40.75 41.25] [ 40.25 40.75 41.25] [ 40.25 40.75 41.25]] [[-1.25 -1.25 -1.25] [-0.75 -0.75 -0.75] [-0.25 -0.25 -0.25] [ 0.25 0.25 0.25] [ 0.75 0.75 0.75]] [ 40.25 41.25] [-1.25 -0.25 0.25] ['41.25 N', '40.25 N'] ['0,25 E', '0.25 W', '1.25 W'] Latitude Longitude """ fname = 'transform' #print fname + ' Lluis: input values trans:', trans, 'dxv:', dxv, 'dyv:', dyv, 'dxt', dxt, 'dyt', dyt, 'dxl', dxl, \ # 'dyl', dyl, 'dxtit', dxtit, 'dytit', dytit, 'axxkind', axxkind, 'axykind', axykind transforms = trans.split('|') Ntransforms = len(transforms) newvals = vals.copy() # values wdvx = False if type(dxv) == type('S') and dxv == '0': newdxv = None else: newdxv = dxv.copy() wdvx = True wdvy = False if type(dyv) == type('S') and dyv == '0': newdyv = None else: newdyv = dyv.copy() wdvy = True # ticks wdtx = False if type(dxt) == type('S') and dxt == '0': newdxt = None else: newdxt = dxt.copy() wdtx = True wdty = False if type(dyt) == type('S') and dyt == '0': newdyt = None else: newdyt = dyt.copy() wdty = True # label in ticks wdlx = False if type(dxl) == type('S') and dxl == '0': newdxl = None else: newdxl = list(dxl) wdlx = True wdly = False if type(dyl) == type('S') and dyl == '0': newdyl = None else: newdyl = list(dyl) wdly = True # axes' title wdTx = False if dxtit != 0: newdxtit = str(dxtit) wdTx = True # print fname + ': Lluis hey:', newdxtit else: newdxtit = None wdTy = False if dytit != '0': newdytit = str(dytit) wdTy = True # print fname + ': Lluis hey:', newdytit else: newdytit = None dx = newvals.shape[0] dy = newvals.shape[1] for transform in transforms: if transform == 'transpose': newvals = np.transpose(newvals) if wdvx and wdvy: copy = newdxv.copy() newdxv = np.transpose(newdyv) newdyv = np.transpose(copy) # else: # print errormsg # print ' ' + fname + ": it can not be '" + transform + "' without " +\ # ' both dimxvals:', dxv, ' and dimyvals:', dyv, ' !!' # quit(-1) if wdtx and wdtx: copy = newdxt.copy() newdxt = np.transpose(newdyt) newdyt = np.transpose(copy) # else: # print errormsg # print ' ' + fname + ": it can not be '" + transform + "' without " +\ # ' both dimxtickvals:', dxt, ' and dimytickvals:', dyt, ' !!' # quit(-1) if wdlx and wdly: copy = list(newdxl) newdxl = list(newdyl) newdyl = list(copy) # else: # print errormsg # print ' ' + fname + ": it can not be '" + transform + "' without " +\ # ' both dimxlabels:', dxl, ' and dimylabels:', dyl, ' !!' # quit(-1) if wdTx and wdTy: copy = str(newdxtit) newdxtit = str(newdytit) newdytit = str(copy) # else: # print errormsg # print ' ' + fname + ": it can not be '" + transform + "' without " +\ # ' both dimx title:', dxtit, ' and dimytitle:', dytit, ' !!' # quit(-1) elif transform[0:4] == 'flip': if transform.find('@') == -1: print errormsg print ' ' + fname + ": no ax given for '" + transform + "' !!" quit(-1) flip = transform.split('@')[1] if flip == 'x': newvals = newvals[...,::-1] if wdvx: if len(newdxv.shape) > 1: newdxv = newdxv[...,::-1] else: newdxv = newdxv[::-1] if wdtx: newdxt = newdxt[::-1] elif flip == 'y': newvals = newvals[...,::-1,:] #if wdvy: # if len(newdyv.shape) > 1: # newdyv = newdyv[...,::-1] # else: # newdyv = newdyv[::-1] #if wdty: # newdyt = newdyt[::-1] #if wdly: # newdyl = newdyl[::-1] elif flip == 'z': newvals = newvals[...,::-1,:,:] else: print errormsg print ' '+ fname + ": transformation '" + transform + "' not ready!!" print ' available ones:', ['transpose', 'flip@x', 'flip@y'] quit(-1) #print fname + ' Lluis: newdxv:', newdxv, 'newdyv:', newdyv, 'newdxt:', newdxt, 'newdyt:', newdyt, \ # 'newdxl', newdxl, 'newdyl', newdyl, 'newdxtit', newdxtit, 'newdytit', newdytit return newvals, newdxv, newdyv, newdxt, newdyt, newdxl, newdyl, newdxtit, newdytit #mat = np.arange(15).reshape(3,5) #xvals = np.zeros((3,5), dtype=np.float) #yvals = np.zeros((3,5), dtype=np.float) #for i in range(5): # xvals[:,i] = -1.25 + i*0.5 #for j in range(3): # yvals[j,:] = 40.25 + j*0.5 #xticks = np.array([-1.25, -0.25, 0.25]) #yticks = np.array([40.25, 41.25]) #xticklab = ['1.25 W', '0.25 W', '0,25 E'] #yticklab = ['40.25 N', '41.25 N'] #xtit = 'Longitude' #ytit = 'Latitude' #nv, ndxv, ndyv, ndxt, ndyt, dxl, ndyl, ndxT, ndyT = transform(mat, 'flip@y', \ # xvals, yvals, xticks, yticks, xticklab, yticklab, xtit, ytit) # #print nv, ndxv, ndyv, ndxt, ndyt, dxl, ndyl, ndxT, ndyT #quit() def legend_values(legstring, char): """ Function to determine the values for the legend legstring= char separated list of [locleg][char][fontsize]: [locleg]: location of the legend (0, automatic) 1: 'upper right', 2: 'upper left', 3: 'lower left', 4: 'lower right', 5: 'right', 6: 'center left', 7: 'center right', 8: 'lower center', 9: 'upper center', 10: 'center' [fontsize]: font size for the legend ('auto' for 12) char= separation character """ fname = 'legend_values' locleg = int(legstring.split(char)[0]) fontsize0 = legstring.split(char)[1] if fontsize0 == 'auto': fontsize = 12 else: fontsize = int(fontsize0) return locleg, fontsize ####### ####### ####### ####### ####### ####### ####### ####### ####### ####### def check_colorBar(cbarn): """ Check if the given colorbar exists in matplotlib """ fname = 'check_colorBar' # FROM: http://matplotlib.org/1.2.1/examples/pylab_examples/show_colormaps.html # Get a list of the colormaps in matplotlib. Ignore the ones that end with # '_r' because these are simply reversed versions of ones that don't end # with '_r' maps = sorted(m for m in plt.cm.datad if not m.endswith("_r")) nmaps = len(maps) + 1 # Possible color bars # colorbars = ['binary', 'Blues', 'BuGn', 'BuPu', 'gist_yarg', 'GnBu', 'Greens', \ # 'Greys', 'Oranges', 'OrRd', 'PuBu', 'PuBuGn', 'PuRd', 'Purples', 'RdPu', \ # 'Reds', 'YlGn', 'YlGnBu', 'YlOrBr', 'YlOrRd', 'afmhot', 'autumn', 'bone', \ # 'cool', 'copper', 'gist_gray', 'gist_heat', 'gray', 'hot', 'pink', 'spring', \ # 'summer', 'winter', 'BrBG', 'bwr', 'coolwarm', 'PiYG', 'PRGn', 'PuOr', 'RdBu', \ # 'RdGy', 'RdYlBu', 'RdYlGn', 'seismic', 'Accent', 'Dark2', 'hsv', 'Paired', \ # 'Pastel1', 'Pastel2', 'Set1', 'Set2', 'Set3', 'spectral', 'gist_earth', \ # 'gist_ncar', 'gist_rainbow', 'gist_stern', 'jet', 'brg', 'CMRmap', 'cubehelix',\ # 'gnuplot', 'gnuplot2', 'ocean', 'rainbow', 'terrain', 'flag', 'prism'] Lcbarn = len(cbarn) if cbarn[Lcbarn-2:Lcbarn] == '_r': cbarn = cbarn[0:Lcbarn-2] if not searchInlist(maps,cbarn): print warnmsg print ' ' + fname + ' color bar: "' + cbarn + '" does not exist !!' print " the standard 'rainbow' will be use instead !!" print ' colorbars availables with this version:', maps quit(-1) return def colorbar_vals(colorbarvs,splitchar): """ Function to provide the colorbar values for a figure colorbarvs= [splitchar] separated list of different colorbar values [cbn]: name of the color bar to use [fmtcb]: format of the tick labels in the colorbar ('C'-like) ('auto' for '%6g') [cbor]: orientation of the color bar ('vertical'/'horizontal') ('auto' for vertical) """ fname = 'colorbar_vals' colbarn = colorbarvs.split(splitchar)[0] fmtcolbar0 = colorbarvs.split(splitchar)[1] colbaror0 = colorbarvs.split(splitchar)[2] if fmtcolbar0 == 'auto': fmtcolbar = '%6g' else: fmtcolbar = fmtcolbar0 if colbaror0 == 'auto': colbaror = 'vertical' else: colbaror = colbaror0 # check colorbar existence check_colorBar(colbarn) return colbarn, fmtcolbar, colbaror def units_lunits(u): """ Function to provide LaTeX equivalences from a given units u= units to transform >>> units_lunits('kgkg-1') '$kgkg^{-1}$' """ fname = 'units_lunits' if u == 'h': print fname + '_____________________________________________________________' print units_lunits.__doc__ quit() # Units which does not change same = ['1', 'category', 'cm', 'counts', 'day', 'deg', 'degree', 'degrees', \ 'degrees East', 'degrees Nord', 'degrees North', 'g', 'gpm', 'hour', 'hPa', \ 'J', 'K', 'Km', 'kg', 'km', 'm', 'minute', 'mm', 'month', 'Pa', 'rad', 's', \ 'second', 'um', 'x', 'y', 'year', '-'] if searchInlist(same,u): lu = '$' + u + '$' elif len(u.split(' ')) > 1 and u.split(' ')[1] == 'since': uparts = u.split(' ') ip=0 for up in uparts: if ip == 0: lu = '$' + up else: lu = lu + '\ ' + up ip=ip+1 lu = lu + '$' else: if u == '': lu='-' elif u == 'C': lu='$^{\circ}C$' elif u == 'days': lu='$day$' elif u == 'Degrees': lu='$degrees$' elif u == 'grid box centre degrees east': lu='$degrees\ East$' elif u == 'degrees_East': lu='$degrees\ East$' elif u == 'degrees_east': lu='$degrees\ East$' elif u == 'degree_east': lu='$degrees\ East$' elif u == 'degree east': lu='$degrees\ East$' elif u == 'degrees longitude': lu='$degrees\ East$' elif u == 'degrees latitude': lu='$degrees\ North$' elif u == 'grid box centre degrees north': lu='$degrees\ North$' elif u == 'degrees_North': lu='$degrees\ North$' elif u == 'degrees_north': lu='$degrees\ North$' elif u == 'degree_north': lu='$degrees\ North$' elif u == 'degree north': lu='$degrees\ North$' elif u == 'deg C': lu='$^{\circ}C$' elif u == 'degC': lu='$^{\circ}C$' elif u == 'deg K': lu='$K$' elif u == 'degK': lu='$K$' elif u == 'g/g': lu='$gg^{-1}$' elif u == 'gC/m^2': lu='$gCm^{-2}$' elif u == 'gC/day/m^2': lu='$gCday^{-1}m^{-2}$' elif u == 'gC/day/(m^2 tot)': lu='$gCday^{-1}(m^{-2}\ tot)$' elif u == 'gC/m^2/pft': lu='$gCm^{-2}pft^{-1}$' elif u == 'hours': lu='$hour$' elif u == 'J/kg': lu='$Jkg^{-1}$' elif u == 'Jkg-1': lu='$Jkg^{-1}$' elif u == 'K/h': lu='$Kh^{-1}$' elif u == 'Kh-1': lu='$Kh^{-1}$' elif u == 'K/m': lu='$Km^{-1}$' elif u == 'Km-1': lu='$Km^{-1}$' elif u == 'Km-3': lu='$Km^{-3}$' elif u == 'K/s': lu='$Ks^{-1}$' elif u == 'Ks-1': lu='$Ks^{-1}$' elif u == 'K s-1': lu='$Ks^{-1}$' elif u == 'K/day': lu='$Kday^{-1}$' elif u == 'Kday-1': lu='$Kday^{-1}$' elif u == 'K day-1': lu='$Kday^{-1}$' elif u == 'kg/kg': lu='$kgkg^{-1}$' elif u == 'kgkg-1': lu='$kgkg^{-1}$' elif u == 'kg kg-1': lu='$kgkg^{-1}$' elif u == '(kg/kg)/s': lu='$kgkg^{-1}s^{-1}$' elif u == 'kgkg-1s-1': lu='$kgkg^{-1}s^{-1}$' elif u == 'kg kg-1 s-1': lu='$kgkg^{-1}s^{-1}$' elif u == 'Kg/m^2': lu='$kgm^{-2}$' elif u == 'kg/m2': lu='$kgm^{-2}$' elif u == 'kgm-2': lu='$kgm^{-2}$' elif u == 'kg m-2': lu='$kgm^{-2}$' elif u == 'Kg m-2': lu='$kgm^{-2}$' elif u == 'kg/m2/s': lu='$kgm^{-2}s^{-1}$' elif u == 'kg/m^2/s': lu='$kgm^{-2}s^{-1}$' elif u == 'kg/(m2*s)': lu='$kgm^{-2}s^{-1}$' elif u == 'kg/(s*m2)': lu='$kgm^{-2}s^{-1}$' elif u == 'kgm-2s-1': lu='$kgm^{-2}s^{-1}$' elif u == 'kg m-2 s-1': lu='$kgm^{-2}s^{-1}$' elif u == 'kg-1 s-1': lu='$kg^{-1}s^{-1}$' elif u == 'kg/dt_sechiba': lu='$kgdt_{sechiba}^{-1}$' elif u == 'kmh-1': lu='$kmh^{-1}$' elif u == 'km h-1': lu='$km h^{-1}$' elif u == '1/m': lu='$m^{-1}$' elif u == 'm-1': lu='$m^{-1}$' elif u == 'm2': lu='$m^{2}$' elif u == 'm^2': lu='$m^{2}$' elif u == 'm2/s': lu='$m2s^{-1}$' elif u == 'm2s-1': lu='$m2s^{-1}$' elif u == 'm2/s2': lu='$m2s^{-2}$' elif u == 'm**2 s**-2': lu='$m2s^{-2}$' elif u == 'm3/s': lu='$m^{3}s^{-1}$' elif u == 'm^3/s': lu='$m^{3}s^{-1}$' elif u == 'm/s': lu='$ms^{-1}$' elif u == 'mmh-3': lu='$mmh^{-3}$' elif u == 'mm/d': lu='$mm\ d^{-1}$' elif u == 'mmd-1': lu='$mm\ d^{-1}$' elif u == 'mm/day': lu='$mm\ day^{-1}$' elif u == 'mmday-1': lu='$mm\ day^{-1}$' elif u == 'mmmon-1': lu='$mm\ mon^{-1}$' elif u == 'mm mon-1': lu='$mm\ mon^{-1}$' elif u == 'mmmonth-1': lu='$mm\ month^{-1}$' elif u == 'mm month-1': lu='$mm\ month^{-1}$' elif u == 'mm yr-1': lu='$mm\ yr^{-1}$' elif u == 'mmyear-1': lu='$mm\ year^{-1}$' elif u == 'mm year-1': lu='$mm\ year^{-1}$' elif u == 'ms-1': lu='$ms^{-1}$' elif u == 'm s-1': lu='$ms^{-1}$' elif u == 'm s**-1': lu='$ms^{-1}$' elif u == 'm/s2': lu='$ms^{-2}$' elif u == 'ms-2': lu='$ms^{-2}$' elif u == 'minutes': lu='$minute$' elif u == 'meters MSL': lu='$m$' elif u == 'No.': lu='$number$' elif u == 'numkg-1': lu='$numkg^{-1}$' elif u == '#kg-1': lu='$numkg^{-1}$' elif u == '\#kg-1': lu='$numkg^{-1}$' elif u == ' kg(-1)': lu='$numkg^{-1}$' elif u == 'numkg-1s-1': lu='$numkg^{-1}s^{-1}$' elif u == '#kg-1 s-1': lu='$numkg^{-1}s^{-1}$' elif u == '\#kg-1 s-1': lu='$numkg^{-1}s^{-1}$' elif u == ' kg(-1) s-1': lu='$numkg^{-1}s^{-1}$' elif u == 'none': lu='-' elif u == 'Pa/s': lu='$Pas^{-1}$' elif u == 'Pas-1': lu='$Pas^{-1}$' elif u == 'W m-2': lu='$Wm^{-2}$' elif u == 'Wm-2': lu='$Wm^{-2}$' elif u == 'W/m2': lu='$Wm^{-2}$' elif u == 'W/m^2': lu='$Wm^{-2}$' elif u == '1/s': lu='$s^{-1}$' elif u == 's-1': lu='$s^{-1}$' elif u == 's-1 ': lu='$s^{-1}$' elif u == 'seconds': lu='$second$' elif u == '%': lu='\%' elif u == '?': lu='-' else: print errormsg print ' ' + fname + ': units "' + u + '" not ready!!!!' Schar = [] for ic in range(len(u)): Schar.append(ord(u[ic:ic+1])) print ' character combination by ASCII numbers: ', Schar quit(-1) return lu def ASCII_LaTeX(ln): """ Function to transform from an ASCII line to LaTeX codification >>> ASCII_LaTeX('Laboratoire de Météorologie Dynamique però Hovmöller') Laboratoire de M\'et\'eorologie Dynamique per\`o Hovm\"oller """ fname='ASCII_LaTeX' if ln == 'h': print fname + '_____________________________________________________________' print ASCII_LaTeX.__doc__ quit() newln = ln.replace('\\', '\\textbackslash') newln = newln.replace('á', "\\'a") newln = newln.replace('é', "\\'e") newln = newln.replace('í', "\\'i") newln = newln.replace('ó', "\\'o") newln = newln.replace('ú', "\\'u") newln = newln.replace('à', "\\`a") newln = newln.replace('è', "\\`e") newln = newln.replace('ì', "\\`i") newln = newln.replace('ò', "\\`o") newln = newln.replace('ù', "\\`u") newln = newln.replace('â', "\\^a") newln = newln.replace('ê', "\\^e") newln = newln.replace('î', "\\^i") newln = newln.replace('ô', "\\^o") newln = newln.replace('û', "\\^u") newln = newln.replace('ä', '\\"a') newln = newln.replace('ë', '\\"e') newln = newln.replace('ï', '\\"i') newln = newln.replace('ö', '\\"o') newln = newln.replace('ü', '\\"u') newln = newln.replace('ç', '\c{c}') newln = newln.replace('ñ', '\~{n}') newln = newln.replace('Á', "\\'A") newln = newln.replace('É', "\\'E") newln = newln.replace('Í', "\\'I") newln = newln.replace('Ó', "\\'O") newln = newln.replace('Ú', "\\'U") newln = newln.replace('À', "\\`A") newln = newln.replace('È', "\\`E") newln = newln.replace('Ì', "\\`I") newln = newln.replace('Ò', "\\`O") newln = newln.replace('Ù', "\\`U") newln = newln.replace('Â', "\\^A") newln = newln.replace('Ê', "\\^E") newln = newln.replace('Î', "\\^I") newln = newln.replace('Ô', "\\^O") newln = newln.replace('Û', "\\^U") newln = newln.replace('Ä', '\\"A') newln = newln.replace('Ë', '\\"E') newln = newln.replace('Ï', '\\"I') newln = newln.replace('Ö', '\\"O') newln = newln.replace('Ü', '\\"U') newln = newln.replace('Ç', '\\c{C}') newln = newln.replace('Ñ', '\\~{N}') newln = newln.replace('¡', '!`') newln = newln.replace('¿', '¿`') newln = newln.replace('%', '\\%') newln = newln.replace('#', '\\#') newln = newln.replace('&', '\\&') newln = newln.replace('$', '\\$') newln = newln.replace('_', '\\_') newln = newln.replace('·', '\\textperiodcentered') newln = newln.replace('<', '$<$') newln = newln.replace('>', '$>$') newln = newln.replace('', '*') # newln = newln.replace('º', '$^{\\circ}$') newln = newln.replace('ª', '$^{a}$') newln = newln.replace('º', '$^{o}$') newln = newln.replace('°', '$^{\\circ}$') newln = newln.replace('\n', '\\\\\n') newln = newln.replace('\t', '\\medskip') return newln def DegGradSec_deg(grad,deg,sec): """ Function to transform from a coordinate in grad deg sec to degrees (decimal) >>> DegGradSec_deg(39.,49.,26.) 39.8238888889 """ fname = 'DegGradSec_deg' if grad == 'h': print fname + '_____________________________________________________________' print DegGradSec_deg.__doc__ quit() deg = grad + deg/60. + sec/3600. return deg def intT2dt(intT,tu): """ Function to provide an 'timedelta' object from a given interval value intT= interval value tu= interval units, [tu]= 'd': day, 'w': week, 'h': hour, 'i': minute, 's': second, 'l': milisecond >>> intT2dt(3.5,'s') 0:00:03.500000 >>> intT2dt(3.5,'w') 24 days, 12:00:00 """ import datetime as dt fname = 'intT2dt' if tu == 'w': dtv = dt.timedelta(weeks=np.float(intT)) elif tu == 'd': dtv = dt.timedelta(days=np.float(intT)) elif tu == 'h': dtv = dt.timedelta(hours=np.float(intT)) elif tu == 'i': dtv = dt.timedelta(minutes=np.float(intT)) elif tu == 's': dtv = dt.timedelta(seconds=np.float(intT)) elif tu == 'l': dtv = dt.timedelta(milliseconds=np.float(intT)) else: print errormsg print ' ' + fname + ': time units "' + tu + '" not ready!!!!' quit(-1) return dtv def lonlat_values(mapfile,lonvn,latvn): """ Function to obtain the lon/lat matrices from a given netCDF file lonlat_values(mapfile,lonvn,latvn) [mapfile]= netCDF file name [lonvn]= variable name with the longitudes [latvn]= variable name with the latitudes """ fname = 'lonlat_values' if mapfile == 'h': print fname + '_____________________________________________________________' print lonlat_values.__doc__ quit() if not os.path.isfile(mapfile): print errormsg print ' ' + fname + ": map file '" + mapfile + "' does not exist !!" quit(-1) ncobj = NetCDFFile(mapfile, 'r') lonobj = ncobj.variables[lonvn] latobj = ncobj.variables[latvn] if len(lonobj.shape) == 3: lonv = lonobj[0,:,:] latv = latobj[0,:,:] elif len(lonobj.shape) == 2: lonv = lonobj[:,:] latv = latobj[:,:] elif len(lonobj.shape) == 1: lon0 = lonobj[:] lat0 = latobj[:] lonv = np.zeros( (len(lat0),len(lon0)), dtype=np.float ) latv = np.zeros( (len(lat0),len(lon0)), dtype=np.float ) for iy in range(len(lat0)): lonv[iy,:] = lon0 for ix in range(len(lon0)): latv[:,ix] = lat0 else: print errormsg print ' ' + fname + ': lon/lat variables shape:',lonobj.shape,'not ready!!' quit(-1) return lonv, latv def date_CFtime(ind,refd,tunits): """ Function to transform from a given date object a CF-convention time ind= date object to transform refd= reference date tunits= units for time >>> date_CFtime(dt.datetime(1976,02,17,08,30,00), dt.datetime(1949,12,01,00,00,00), 'seconds') 827224200.0 """ import datetime as dt fname = 'date_CFtime' dt = ind - refd if tunits == 'weeks': value = dt.days/7. + dt.seconds/(3600.*24.*7.) elif tunits == 'days': value = dt.days + dt.seconds/(3600.*24.) elif tunits == 'hours': value = dt.days*24. + dt.seconds/(3600.) elif tunits == 'minutes': value = dt.days*24.*60. + dt.seconds/(60.) elif tunits == 'seconds': value = dt.days*24.*3600. + dt.seconds elif tunits == 'milliseconds': value = dt.days*24.*3600.*1000. + dt.seconds*1000. else: print errormsg print ' ' + fname + ': reference time units "' + trefu + '" not ready!!!!' quit(-1) return value def pot_values(values, uvals): """ Function to modify a seies of values by their potency of 10 pot_values(values, uvals) values= values to modify uvals= units of the values >>> vals = np.sin(np.arange(20)*np.pi/5.+0.01)*10.e-5 >>> pot_values(vals,'ms-1') (array([ 0.00000000e+00, 5.87785252e-01, 9.51056516e-01, 9.51056516e-01, 5.87785252e-01, 1.22464680e-16, -5.87785252e-01, -9.51056516e-01, -9.51056516e-01, -5.87785252e-01, -2.44929360e-16, 5.87785252e-01, 9.51056516e-01, 9.51056516e-01, 5.87785252e-01, 3.67394040e-16, -5.87785252e-01, -9.51056516e-01, -9.51056516e-01, -5.87785252e-01]), -4, 'x10e-4 ms-1', 'x10e-4') """ fname = 'pot_values' if np.min(values) != 0.: potmin = int( np.log10( np.abs(np.min(values)) ) ) else: potmin = 0 if np.max(values) != 0.: potmax = int( np.log10( np.abs(np.max(values)) ) ) else: potmax = 0 if potmin * potmax > 9: potval = -np.min([np.abs(potmin), np.abs(potmax)]) * np.abs(potmin) / potmin newvalues = values*10.**potval potvalue = - potval potS = 'x10e' + str(potvalue) newunits = potS + ' ' + uvals else: newvalues = values potvalue = None potS = '' newunits = uvals return newvalues, potvalue, newunits, potS def CFtimes_plot(timev,units,kind,tfmt): """ Function to provide a list of string values from a CF time values in order to use them in a plot, according to the series of characteristics. String outputs will be suited to the 'human-like' output timev= time values (real values) units= units string according to CF conventions ([tunits] since [YYYY]-[MM]-[DD] [[HH]:[MI]:[SS]]) kind= kind of output 'Nval': according to a given number of values as 'Nval',[Nval] 'exct': according to an exact time unit as 'exct',[tunit]; tunit= [Nunits],[tu]; [tu]= 'c': centuries, 'y': year, 'm': month, 'w': week, 'd': day, 'h': hour, 'i': minute, 's': second, 'l': milisecond tfmt= desired format >>> CFtimes_plot(np.arange(100)*1.,'hours since 1979-12-01 00:00:00', 'Nval,5',"%Y/%m/%d %H:%M:%S") 0.0 1979/12/01 00:00:00 24.75 1979/12/02 00:45:00 49.5 1979/12/03 01:30:00 74.25 1979/12/04 02:15:00 99.0 1979/12/05 03:00:00 >>> CFtimes_plot(np.arange(100)*1.,'hours since 1979-12-01 00:00:00', 'exct,2,d',"%Y/%m/%d %H:%M:%S") 0.0 1979/12/01 00:00:00 48.0 1979/12/03 00:00:00 96.0 1979/12/05 00:00:00 144.0 1979/12/07 00:00:00 """ import datetime as dt # Seconds between 0001 and 1901 Jan - 01 secs0001_1901=59958144000. fname = 'CFtimes_plot' if type(timev) == type('S') and timev == 'h': print fname + '_____________________________________________________________' print CFtimes_plot.__doc__ quit() secsYear = 365.*24.*3600. secsWeek = 7.*24.*3600. secsDay = 24.*3600. secsHour = 3600. secsMinute = 60. secsMilisecond = 1./1000. secsMicrosecond = 1./1000000. # Does reference date contain a time value [YYYY]-[MM]-[DD] [HH]:[MI]:[SS] ## trefT = units.find(':') txtunits = units.split(' ') Ntxtunits = len(txtunits) if Ntxtunits == 3: Srefdate = txtunits[Ntxtunits - 1] else: Srefdate = txtunits[Ntxtunits - 2] if not trefT == -1: # print ' ' + fname + ': refdate with time!' if Ntxtunits == 3: refdate = datetimeStr_datetime(Srefdate) else: refdate = datetimeStr_datetime(Srefdate + '_' + txtunits[Ntxtunits - 1]) else: refdate = datetimeStr_datetime(Srefdate + '_00:00:00') trefunits=units.split(' ')[0] if trefunits == 'weeks': trefu = 'w' elif trefunits == 'days': trefu = 'd' elif trefunits == 'hours': trefu = 'h' elif trefunits == 'minutes': trefu = 'm' elif trefunits == 'seconds': trefu = 's' elif trefunits == 'milliseconds': trefu = 'l' else: print errormsg print ' ' + fname + ': reference time units "' + trefu + '" not ready!!!!' quit(-1) okind=kind.split(',')[0] dtv = len(timev) if refdate.year == 1: print warnmsg print ' ' + fname + ': changing reference date: ',refdate, \ 'to 1901-01-01_00:00:00 !!!' refdate = datetimeStr_datetime('1901-01-01_00:00:00') if trefu == 'w': timev = timev - secs0001_1901/(7.*24.*3600.) if trefu == 'd': timev = timev - secs0001_1901/(24.*3600.) if trefu == 'h': timev = timev - secs0001_1901/(3600.) if trefu == 'm': timev = timev - secs0001_1901/(60.) if trefu == 's': timev = timev - secs0001_1901 if trefu == 'l': timev = timev - secs0001_1901*1000. # if refdate.year < 1901: # print warnmsg # print ' ' + fname + ': changing reference date: ',refdate, \ # 'to 1901-01-01_00:00:00 !!!' # diffrefs = dt.datetime(1901,1,1,0,0,0) - refdate # if gen.searchInlist(dir(diffrefs), 'total_seconds'): # secsref_1901 = diffrefs.total_seconds() # else: # secsref_1901 = diffrefs.days()*3600*24. + diffrefs.seconds()*1. # refdate = datetimeStr_datetime('1901-01-01_00:00:00') # print 'time 0 :', timev[0] # if trefu == 'w': timev = timev - secsref_1901/(7.*24.*3600.) # if trefu == 'd': timev = timev - secsref_1901/(24.*3600.) # if trefu == 'h': timev = timev - secsref_1901/(3600.) # if trefu == 'm': timev = timev - secsref_1901/(60.) # if trefu == 's': timev = timev - secsref_1901 # if trefu == 'l': timev = timev - secsref_1901*1000. # print 'time 0 after:', timev[0] firstT = timev[0] secondT = timev[1] lastT = timev[dtv-1] # First and last times as datetime objects firstTdt = timeref_datetime(refdate, firstT, trefunits) secondTdt = timeref_datetime(refdate, secondT, trefunits) lastTdt = timeref_datetime(refdate, lastT, trefunits) # Difference between second and first time-step dt12 = secondTdt - firstTdt if searchInlist(dir(dt12), 'total_seconds'): diff12 = dt12.total_seconds() else: diff12 = dt12.days*24.*3600. + dt12.seconds # First and last times as [year, mon, day, hour, minut, second] vectors firstTvec = np.zeros((6), dtype= np.float) lastTvec = np.zeros((6), dtype= np.float) chTvec = np.zeros((6), dtype= bool) firstTvec = np.array([firstTdt.year, firstTdt.month, firstTdt.day, firstTdt.hour,\ firstTdt.minute, firstTdt.second]) lastTvec = np.array([lastTdt.year, lastTdt.month, lastTdt.day, lastTdt.hour, \ lastTdt.minute, lastTdt.second]) chdate= lastTvec - firstTvec chTvec = np.where (chdate != 0., True, False) TOTdt = lastTdt - firstTdt TOTdtsecs = TOTdt.days*secsDay + TOTdt.seconds + TOTdt.microseconds*secsMicrosecond timeout = [] if okind == 'Nval': nvalues = int(kind.split(',')[1]) intervT = (lastT - firstT)/(nvalues-1) dtintervT = intT2dt(intervT, trefu) for it in range(nvalues): timeout.append(firstTdt + dtintervT*it) elif okind == 'exct': Nunits = int(kind.split(',')[1]) tu = kind.split(',')[2] # Generic incremental dt [seconds] according to all the possibilities ['c', 'y', 'm', # 'w', 'd', 'h', 'i', 's', 'l'], some of them approximated (because they are not # already necessary!) basedt = np.zeros((9), dtype=np.float) basedt[0] = (365.*100. + 25.)*24.*3600. basedt[1] = secsYear basedt[2] = 31.*24.*3600. basedt[3] = secsWeek basedt[4] = secsDay basedt[5] = secsHour basedt[6] = secsMinute basedt[7] = 1. basedt[8] = secsMilisecond # Increment according to the units of the CF dates if trefunits == 'weeks': basedt = basedt/(secsWeek) elif trefunits == 'days': basedt = basedt/(secsDay) elif trefunits == 'hours': basedt = basedt/(secsHour) elif trefunits == 'minutes': basedt = basedt/(secsMinute) elif trefunits == 'seconds': basedt = basedt elif trefunits == 'milliseconds': basedt = basedt*secsMilisecond if tu == 'c': ti = firstTvec[0] tf = lastTvec[0] centi = firstTvec[0] / 100 datev = firstTdt while datev < lastTdt: yr = datev.year + Nunits*100 mon = datev.month datev = dt.datetime(yr, mon, 1, 0, 0, 0) timeout.append(datev) elif tu == 'y': ti = firstTvec[0] tf = lastTvec[0] year = firstTvec[0] TOTsteps = int(TOTdtsecs/(Nunits*31*secsDay)) + 1 if np.sum(firstTvec[1:5]) > 0: firstTdt = dt.datetime(year, 1, 1, 0, 0, 0) datev = dt.datetime(year, 1, 1, 0, 0, 0) datev = firstTdt timeout.append(datev) yr = datev.year while yr + Nunits <= tf : yr = datev.year + Nunits mon = datev.month datev = dt.datetime(yr, mon, 1, 0, 0, 0) timeout.append(datev) elif tu == 'm': ti = firstTvec[1] tf = lastTvec[1] yr = firstTvec[0] mon = firstTvec[1] TOTsteps = int(TOTdtsecs/(Nunits*31*secsDay)) + 1 datev = firstTdt while datev < lastTdt: mon = datev.month + Nunits if mon > 12: yr = yr + 1 mon = 1 datev = dt.datetime(yr, mon, 1, 0, 0, 0) timeout.append(datev) elif tu == 'w': datev=firstTdt it=0 while datev <= lastTdt: datev = firstTdt + dt.timedelta(days=7*Nunits*it) timeout.append(datev) it = it + 1 elif tu == 'd': # datev=firstTdt yr = firstTvec[0] mon = firstTvec[1] day = firstTvec[2] Iunits = np.mod(day,Nunits) if np.sum(firstTvec[2:5]) > 0: firstTdt = dt.datetime(yr, mon, day+1, 0, 0, 0) datev = dt.datetime(yr, mon, day+1, 0, 0, 0) elif Iunits != 0: nNunits = int(day/Nunits) firstTdt = dt.datetime(yr, mon, nNunits*Nunits, 0, 0, 0) datev = dt.datetime(yr, mon, nNunits*Nunits, 0, 0, 0) else: firstTdt = dt.datetime(yr, mon, day, 0, 0, 0) datev = dt.datetime(yr, mon, day, 0, 0, 0) it=0 while datev <= lastTdt: datev = firstTdt + dt.timedelta(days=Nunits*it) timeout.append(datev) it = it + 1 elif tu == 'h': datev=firstTdt yr = firstTvec[0] mon = firstTvec[1] day = firstTvec[2] hour = firstTvec[3] Iunits = np.mod(hour,Nunits) if np.sum(firstTvec[4:5]) > 0 or Iunits != 0: tadvance = 2*Nunits if tadvance >= 24: firstTdt = dt.datetime(yr, mon, day+1, 0, 0, 0) datev = dt.datetime(yr, mon, day+1, 0, 0, 0) else: nNunits = int(hour/Nunits) firstTdt = dt.datetime(yr, mon, day, nNunits*Nunits, 0, 0) datev = dt.datetime(yr, mon, day, nNunits*Nunits, 0, 0) else: firstTdt = dt.datetime(yr, mon, day, hour, 0, 0) datev = dt.datetime(yr, mon, day, hour, 0, 0) it=0 while datev <= lastTdt: datev = firstTdt + dt.timedelta(seconds=Nunits*3600*it) timeout.append(datev) it = it + 1 elif tu == 'i': datev=firstTdt yr = firstTvec[0] mon = firstTvec[1] day = firstTvec[2] hour = firstTvec[3] minu = firstTvec[4] Iunits = np.mod(minu,Nunits) if firstTvec[5] > 0 or Iunits != 0: tadvance = 2*Nunits if tadvance >= 60: firstTdt = dt.datetime(yr, mon, day, hour, 0, 0) datev = dt.datetime(yr, mon, day, hour, 0, 0) else: nNunits = int(minu/Nunits) firstTdt = dt.datetime(yr, mon, day, hour, nNunits*Nunits, 0) datev = dt.datetime(yr, mon, day, hour, nNunits*Nunits, 0) else: firstTdt = dt.datetime(yr, mon, day, hour, minu, 0) datev = dt.datetime(yr, mon, day, hour, minu, 0) it=0 while datev <= lastTdt: datev = firstTdt + dt.timedelta(seconds=Nunits*60*it) timeout.append(datev) it = it + 1 elif tu == 's': datev=firstTdt yr = firstTvec[0] mon = firstTvec[1] day = firstTvec[2] hour = firstTvec[3] minu = firstTvec[4] secu = firstTvec[5] Iunits = np.mod(secu,Nunits) if firstTvec[5] > 0 or Iunits != 0: tadvance = 2*Nunits if tadvance >= 60: firstTdt = dt.datetime(yr, mon, day, hour, minu, 0) datev = dt.datetime(yr, mon, day, hour, minu, 0) else: nNunits = int(minu/Nunits) firstTdt = dt.datetime(yr, mon, day, hour, minu, nNunits*Nunits) datev = dt.datetime(yr, mon, day, hour, minu, nNunits*Nunits) else: firstTdt = dt.datetime(yr, mon, day, hour, minu, secu) datev = dt.datetime(yr, mon, day, hour, minu, secu) it=0 while datev <= lastTdt: datev = firstTdt + dt.timedelta(seconds=Nunits*it) timeout.append(datev) it = it + 1 elif tu == 'l': datev=firstTdt it=0 while datev <= lastTdt: datev = firstTdt + dt.timedelta(seconds=Nunits*it/1000.) timeout.append(datev) it = it + 1 else: print errormsg print ' ' + fname + ': exact units "' + tu + '" not ready!!!!!' quit(-1) else: print errormsg print ' ' + fname + ': output kind "' + okind + '" not ready!!!!' quit(-1) dtout = len(timeout) timeoutS = [] timeoutv = np.zeros((dtout), dtype=np.float) for it in range(dtout): timeoutS.append(timeout[it].strftime(tfmt)) timeoutv[it] = date_CFtime(timeout[it], refdate, trefunits) # print it,':',timeoutv[it], timeoutS[it] if len(timeoutv) <= 1 or len(timeoutS) <= 1: print errormsg print ' ' + fname + ": no `time-labels' values are generated !!" print ' passed configuration does not conform time-data' print ' input data:' print ' number of values passed:', len(timev) print ' units:',units print ' desired output:' print ' kind of labels:',kind print ' format:',tfmt print ' function values ___ __ _' print ' time reference date:',refdate print ' first date in input data:',firstTdt print ' last date in input data:',lastTdt print ' period in input data:', lastTdt - firstTdt print ' time difference between first and second time-step:', dt12, \ '==>', diff12, 'seconds' print ' Provide new parameters in order to obtain time-labels' quit(-1) return timeoutv, timeoutS def color_lines(Nlines): """ Function to provide a color list to plot lines color_lines(Nlines) Nlines= number of lines """ fname = 'color_lines' colors = ['r', 'b', 'g', 'p', 'g'] colorv = [] colorv.append('k') for icol in range(Nlines): colorv.append(colors[icol]) return colorv def output_kind(kindf, namef, close): """ Function to generate the output of the figure kindf= kind of the output null: show in screen [jpg/pdf/png/ps]: standard output types namef= name of the figure (without extension) close= if the graph has to be close or not [True/False] """ fname = 'output_kind' if kindf == 'h': print fname + '_____________________________________________________________' print output_kind.__doc__ quit() if close: if kindf == 'null': print 'showing figure...' plt.show() elif kindf == 'gif': plt.savefig(namef + ".gif") if close: print "Successfully generation of figure '" + namef + ".jpg' !!!" elif kindf == 'jpg': plt.savefig(namef + ".jpg") if close: print "Successfully generation of figure '" + namef + ".jpg' !!!" elif kindf == 'pdf': plt.savefig(namef + ".pdf") if close: print "Successfully generation of figure '" + namef + ".pdf' !!!" elif kindf == 'png': plt.savefig(namef + ".png") if close: print "Successfully generation of figure '" + namef + ".png' !!!" elif kindf == 'ps': plt.savefig(namef + ".ps") if close: print "Successfully generation of figure '" + namef + ".ps' !!!" else: print errormsg print ' ' + fname + ' output format: "' + kindf + '" not ready !!' print errormsg quit(-1) plt.close() return def check_arguments(funcname,args,expectargs,char): """ Function to check the number of arguments if they are coincident check_arguments(funcname,Nargs,args,char) funcname= name of the function/program to check args= passed arguments expectargs= expected arguments char= character used to split the arguments """ fname = 'check_arguments' Nvals = len(args.split(char)) Nargs = len(expectargs.split(char)) if Nvals != Nargs: print errormsg print ' ' + fname + ': wrong number of arguments:',Nvals," passed to '", \ funcname, "' which requires:",Nargs,'!!' print ' # given expected _______' Nmax = np.max([Nvals, Nargs]) for ia in range(Nmax): if ia > Nvals-1: aval = ' ' else: aval = args.split(char)[ia] if ia > Nargs-1: aexp = ' ' else: aexp = expectargs.split(char)[ia] print ' ', ia, aval, aexp quit(-1) return def Str_Bool(val): """ Function to transform from a String value to a boolean one >>> Str_Bool('True') True >>> Str_Bool('0') False >>> Str_Bool('no') False """ fname = 'Str_Bool' if val == 'True' or val == 'true' or val == '1' or val == 'yes': boolv = True elif val == 'False' or val == 'false' or val == '0' or val== 'no': boolv = False else: print errormsg print ' ' + fname + ": value '" + val + "' not ready!!" quit(-1) return boolv def graphic_range(vrng,varsV): """ Function to provide the ranges of a figure following different options vrng: list of two values: maximum and minimum for the range of the figure 'Srange': for full range 'Saroundmean@val': for mean-xtrm,mean+xtrm where xtrm = np.min(mean-min@val,max@val-mean) 'Saroundminmax@val': for min*val,max*val 'Saroundpercentile@val': for median-xtrm,median+xtrm where xtrm = np.min(median-percentile_(val), percentile_(100-val)-median) 'Smean@val': for -xtrm,xtrm where xtrm = np.min(mean-min*@val,max*@val-mean) 'Smedian@val': for -xtrm,xtrm where xtrm = np.min(median-min@val,max@val-median) 'Spercentile@val': for -xtrm,xtrm where xtrm = np.min(median-percentile_(val), percentile_(100-val)-median) """ fname = 'graphic_range' rangegrph = np.zeros((2), dtype=np.float) # Changing limits of the colors if type(vrng[0]) == type('S') and vrng[0][0:1] == 'S': if vrng[0] == 'Srange': rangegrph[0] = np.min(varsV) rangegrph[1] = np.max(varsV) elif vrng[0][0:11] == 'Saroundmean': meanv = np.mean(varsV) permean = np.float(vrng[0].split('@')[1]) minv = np.min(varsV)*permean maxv = np.max(varsV)*permean minextrm = np.min([np.abs(meanv-minv), np.abs(maxv-meanv)]) rangegrph[0] = meanv-minextrm rangegrph[1] = meanv+minextrm elif vrng[0][0:13] == 'Saroundminmax': permean = np.float(vrng[0].split('@')[1]) minv = np.min(varsV)*permean maxv = np.max(varsV)*permean rangegrph[0] = minv rangegrph[1] = maxv elif vrng[0][0:17] == 'Saroundpercentile': medianv = np.median(varsV) valper = np.float(vrng[0].split('@')[1]) minv = np.percentile(varsV, valper) maxv = np.percentile(varsV, 100.-valper) minextrm = np.min([np.abs(medianv-minv), np.abs(maxv-medianv)]) rangegrph[0] = medianv-minextrm rangegrph[1] = medianv+minextrm elif vrng[0][0:5] == 'Smean': meanv = np.mean(varsV) permean = np.float(vrng[0].split('@')[1]) minv = np.min(varsV)*permean maxv = np.max(varsV)*permean minextrm = np.min([np.abs(meanv-minv), np.abs(maxv-meanv)]) rangegrph[0] = -minextrm rangegrph[1] = minextrm elif vrng[0][0:7] == 'Smedian': medianv = np.median(varsV) permedian = np.float(vrng[0].split('@')[1]) minv = np.min(varsV)*permedian maxv = np.max(varsV)*permedian minextrm = np.min([np.abs(medianv-minv), np.abs(maxv-medianv)]) rangegrph[0] = -minextrm rangegrph[1] = minextrm elif vrng[0][0:11] == 'Spercentile': medianv = np.median(varsV) valper = np.float(vrng[0].split('@')[1]) minv = np.percentile(varsV, valper) maxv = np.percentile(varsV, 100.-valper) minextrm = np.min([np.abs(medianv-minv), np.abs(maxv-medianv)]) rangegrph[0] = -minextrm rangegrph[1] = minextrm else: print errormsg print ' ' + fname + ": range '" + vrng[0] + "' not ready!!!" quit(-1) print ' ' + fname + ': modified min,max:',rangegrph else: rangegrph[0] = np.float(vrng[0]) rangegrph[1] = np.float(vrng[1]) return rangegrph def format_axes(axesS,char): """ Function to provide the format for the ticks of the axes in a figure axesS= [char] separated list of ('auto' for all 'auto' values) xs: style of x-axis ('auto' for 'pretty') 'Nfix', values computed at even 'Ndx' 'Stringlist', a given list of strings 'Vfix', values computed at even 'Ndx' increments 'pretty', values computed following aprox. 'Ndx' at 'pretty' intervals (2.,2.5,4,5,10) xf: format of the ticks labels at the x-axis ('auto' for '5g') Nx: number of ticks labels at the x-axis ('auto' for 5, '@' list of values for 'Stringlist' '!' for spaces) orx: angle of orientation of ticks at the x-axis ('auto' for horizontal) ys: style of y-axis ('auto' for 'pretty') yf: format of the ticks labels at the y-axis ('auto' for '5g') Ny: number of ticks labels at the y-axis ('auto' for 5) ory: angle of orientation of ticks at the y-axis ('auto' for horizontal) >>> format_axes('auto',',') ('pretty', '5g', 5, 0.0, 'pretty', '5g', 5, 0.0) >>> format_axes('pretty,auto,7,auto,Vfix,.0f,30,45.',',') ('pretty', '5g', 7, 0.0, 'Vfix', '.0f', 30, 45.0) """ fname = 'format_axes' if axesS == 'auto': xs = 'pretty' xf = '5g' Nx = 5 orx = 0. ys = 'pretty' yf = '5g' Ny = 5 ory = 0. else: Sv = axesS.split(char) if Sv[0] == 'auto': xs = 'pretty' else: xs = Sv[0] if Sv[1] == 'auto': xf = '5g' else: xf = Sv[1] if Sv[2] == 'auto': Nx = 5 else: if Sv[0] == 'pretty' or Sv[0] == 'Nfix': Nx = int(Sv[2]) elif Sv[0] == 'Stringlist': Nx0 = Sv[2].replace('!', ' ').split('@') Nx = [] for Nxn in Nx0: Nx.append(gen.latex_text(Nxn)) else: Nx = np.float(Sv[2]) if Sv[3] == 'auto': orx = 0. else: orx = np.float(Sv[3]) if Sv[4] == 'auto': ys = 'pretty' else: ys = Sv[4] if Sv[5] == 'auto': yf = '5g' else: yf = Sv[5] if Sv[6] == 'auto': Ny = 5 else: if Sv[4] == 'pretty' or Sv[4] == 'Nfix': Ny = int(Sv[6]) elif Sv[4] == 'Stringlist': Ny0 = Sv[6].replace('!', ' ').split('@') Ny = [] for Nyn in Ny0: Ny.append(gen.latex_text(Nyn)) else: Ny = np.float(Sv[6]) if Sv[7] == 'auto': ory = 0. else: ory = np.float(Sv[7]) return xs, xf, Nx, orx, ys, yf, Ny, ory def pixelgrid(daxisv, axist, axisL, axis, axiskind, trans): """ Function to provide the kind of grid distribution for a plot daxisv: values along the axis of the plot axis: axis of the plot 'x/y' axist: position of the ticks along the axis axisL: limits of the axis axiskind: kind of axis reference 'fixpixel': pixel preserves size all along axis 'data': pixel follows data values (as in a georeferenced map) trans: transformation applied to the axes. '|' separated list of operations of transformation 'transpose': Transpose matrix of values (x-->y, y-->x) 'flip@[x/y]': Flip the given axis output: axisv: resultant values along the axis newaxist: resultant position of the ticks along the axis newaxisL: new limits of the axis """ fname = 'pixelgrid' available = ['data', 'fixpixel'] if not gen.searchInlist(available, axiskind): print errormsg print ' ' +fname+ ": wrong kind of grid-size for axis '" + axiskind + "' !!" print ' available ones:', available quit(-1) if len(daxisv.shape) == 1: dn = daxisv[0] dx = daxisv[len(daxisv)-1] Laxis = daxisv.shape[0] axisint = daxisv if axiskind == 'fixpixel': axisv = np.arange(Laxis, dtype=np.float)/(Laxis-1) elif axiskind == 'data': axisv = daxisv elif len(daxisv.shape) == 2: dn = daxisv[0,0] if axis == 'x': Laxis = daxisv.shape[1] dx = daxisv[0,Laxis-1] axisint = daxisv[0,:] if axiskind == 'fixpixel': for iy in range(daxisv.shape[0]): axisv[iy,:] = np.arange(Laxis, dtype=np.float)/(Laxis-1) elif axiskind == 'data': axisv = daxisv else: Laxis = daxisv.shape[0] dx = daxisv[Laxis-1,0] axisint = daxisv[:,0] if axiskind == 'fixpixel': for ix in range(daxisv.shape[1]): axisv[:,ix] = np.arange(Laxis, dtype=np.float)/(Laxis-1) elif axiskind == 'data': axisv = daxisv transforms = trans.split('|') # Axis ticks and axis range if axiskind == 'fixpixel': newaxist = interpolate_locs(axist,axisint,'lin')/(Laxis-1) if gen.searchInlist(transforms, 'flip@' + axis): newaxisL = np.array([1., 0.]) else: newaxisL = np.array([0., 1.]) elif axiskind == 'data': newaxist = axist newaxisL = axisL return axisv, newaxist, newaxisL ####### ###### ##### #### ### ## # END of GENERIC functions def plot_TimeSeries(valtimes, lnx, vunits, tunits, hfileout, vtit, ttit, tkind, \ tformat, tit, linesn, lloc, lsiz, kfig, coll, typl, ptl, wdtl, ptz, ptf, fclose): """ Function to draw time-series valtimes= list of arrays to plot [vals1[1values, 1times], [...,valsM[Mvals,Mtimes]]) lnx: list with the minimum and maximum values vunits= units of the values tunits= units of the times hfileout= header of the output figure. Final name: [hfileout]_[vtit].[kfig] vtit= variable title to be used in the graph ttit= time title to be used in the graph tkind= kind of time values to appear in the x-axis 'Nval': according to a given number of values as 'Nval',[Nval] 'exct': according to an exact time unit as 'exct',[tunit]; tunit= [Nunits],[tu]; [tu]= 'c': centuries, 'y': year, 'm': month, 'w': week, 'd': day, 'h': hour, 'i': minute, 's': second, 'l': milisecond tformat= desired format of times tit= title of the graph linesn= list of values fot the legend lloc= location of the legend (0, autmoatic) 1: 'upper right', 2: 'upper left', 3: 'lower left', 4: 'lower right', 5: 'right', 6: 'center left', 7: 'center right', 8: 'lower center', 9: 'upper center', 10: 'center' lsiz= font size of the legend kfig= type of figure: jpg, png, pdf, ps coll= ',' list of colors for the lines, 'None' for automatic, single value all the same typl= ',' list of type for the lines, 'None' for automatic, single value all the same ptl= ',' list of type of points for the lines, 'None' for automatic, single value all the same wdtl= ',' list of width for the lines, 'None' for automatic, single value all the same ptz= ',' list of size of points for the lines, 'None' for automatic, single value all the same ptf= frequency of point plotting, 'all' for all time steps fclose= whether figure has to be closed or not """ fname = 'plot_TimeSeries' if valtimes == 'h': print fname + '_____________________________________________________________' print plot_TimeSeries.__doc__ quit() Nlines = len(valtimes) # Lines' characteristics cols, lins, pts, lws, pss = ColorsLinesPointsStyles(Nlines, coll, typl, ptl, wdtl, ptz, ptf) Nvalues = [] Ntimes = [] totvals = [] for il in range(Nlines): array = valtimes[il] totvals = totvals + list(array[0,:]) if Nlines == 1: print warnmsg print ' ' + fname + ': drawing only one line!' Nvalues.append(array.shape[1]) Ntimes.append(array.shape[0]) tmin = np.min(array[1]) tmax = np.max(array[1]) vmin = np.min(array[0]) vmax = np.max(array[0]) else: Nvalues.append(array.shape[1]) Ntimes.append(array.shape[0]) tmin = np.min(array[1,:]) tmax = np.max(array[1,:]) vmin = np.min(array[0,:]) vmax = np.max(array[0,:]) if il == 0: xmin = tmin xmax = tmax ymin = vmin ymax = vmax else: if tmin < xmin: xmin = tmin if tmax > xmax: xmax = tmax if vmin < ymin: ymin = vmin if vmax > ymax: ymax = vmax # Changing limits of the plot vsend = graphic_range(lnx, np.array(totvals)) dx = np.max(Ntimes) dy = np.min(Nvalues) plt.rc('text', usetex=True) if vtit == 'ps': plt.ylim(98000.,ymax) else: plt.ylim(vsend[0],vsend[1]) plt.xlim(xmin,xmax) for il in range(Nlines): array = valtimes[il] if vtit == 'ps': array[0,:] = np.where(array[0,:] < 98000., None, array[0,:]) # plt.plot(array[1,:],array[0,:], lins[il], label=gen.latex_text(linesn[il])) # plt.plot(array[1,::ptf],array[0,::ptf], pointkinds[il], \ # label=gen.latex_text(linesn[il])) plt.plot(array[1,:], array[0,:], lins[il], marker=pts[il], color=cols[il], \ label=gen.latex_text(linesn[il]), linewidth=lws[il], markersize=pss[il], \ markevery=ptf) timevals = np.arange(xmin,xmax)*1. tpos, tlabels = CFtimes_plot(timevals, tunits, tkind, tformat) if len(tpos) > 10: print warnmsg print ' ' + fname + ': with "' + tkind + '" there are', len(tpos), 'xticks !' plt.xticks(tpos, tlabels) # plt.Axes.set_xticklabels(tlabels) plt.legend(loc=lloc, prop={'size':lsiz}) plt.xlabel(ttit) plt.ylabel(gen.latex_text(vtit) + " (" + units_lunits(vunits) + ")") plt.title(tit) figname = hfileout + '_' + vtit output_kind(kfig, figname, fclose) return #Nt = 50 #Nlines = 3 #vtvalsv = [] #valsv = np.zeros((2,Nt), dtype=np.float) ## First #valsv[0,:] = np.arange(Nt) #valsv[1,:] = np.arange(Nt)*180. #vtvalsv.append(valsv) #del(valsv) #valsv = np.zeros((2,Nt/2), dtype=np.float) ## Second #valsv[0,:] = np.arange(Nt/2) #valsv[1,:] = np.arange(Nt/2)*180.*2. #vtvalsv.append(valsv) #del(valsv) #valsv = np.zeros((2,Nt/4), dtype=np.float) ## Third #valsv[0,:] = np.arange(Nt/4) #valsv[1,:] = np.arange(Nt/4)*180.*4. #vtvalsv.append(valsv) #del(valsv) #varu='mm' #timeu='seconds' #title='test' #linesname = ['line 1', 'line 2', 'line 3'] #plot_TimeSeries(vtvalsv, units_lunits(varu), timeu, 'test', 'vartest', 'time', title, linesname, 'png') #quit() def plot_points(xval, yval, vlon, vlat, extravals, extrapar, vtit, xaxv, yaxv, mapv, \ figk, color, labels, lloc, gsize, kfig, figname, ifclose): """ plotting points [x/yval]: x,y values to plot vlon= 2D-matrix with the longitudes vlat= 2D-matrix with the latitudes extravals= extra values to be added into the plot (None for nothing) extrapar= [varname, min, max, cbar, varunits] of the extra variable vtit= title of the graph ('|' for spaces) xaxv= list with the x-axis paramteres [style, format, number and orientation] yaxv= list with the y-axis paramteres [style, format, number and orientation] mapv= map characteristics: [proj],[res] see full documentation: http://matplotlib.org/basemap/ [proj]: projection * 'cyl', cilindric * 'lcc', lambert-conformal [res]: resolution: * 'c', crude * 'l', low * 'i', intermediate * 'h', high * 'f', full figK= kind of figure 'legend': only points in the map with the legend with the names 'labelled',[txtsize],[txtcol]: points with the names and size, color of text color= color for the points/labels ('auto', for "red") labels= list of labels for the points (None, no labels) lloc = localisation of the legend gsize = font size of the legend kfig= kind of figure (jpg, pdf, png) figname= name of the figure ifclose= boolean value whether figure should be close (finish) or not """ fname = 'plot_points' # Axis ticks # Usually axis > x must be the lon, thus... dimxv0 = np.array(xval) dimyv0 = np.array(yval) dxn = dimxv0.min() dxx = dimxv0.max() dyn = dimyv0.min() dyx = dimyv0.max() if xaxv[0] == 'pretty': dimxt0 = np.array(gen.pretty_int(dxn,dxx,xaxv[2])) elif xaxv[0] == 'Nfix': dimxt0 = np.arange(dxn,dxx,(dxx-dxn)/(1.*xaxv[2])) elif xaxv[0] == 'Vfix': dimxt0 = np.arange(0,dxx,xaxv[2]) if yaxv[0] == 'pretty': dimyt0 = np.array(gen.pretty_int(dyn,dyx,yaxv[2])) elif yaxv[0] == 'Nfix': dimyt0 = np.arange(dyn,dyx,(dyx-dyn)/(1.*yaxv[2])) elif yaxv[0] == 'Vfix': dimyt0 = np.arange(0,dyx,yaxv[2]) dimxl0 = [] for i in range(len(dimxt0)): dimxl0.append('{:{style}}'.format(dimxt0[i], style=xaxv[1])) dimyl0 = [] for i in range(len(dimyt0)): dimyl0.append('{:{style}}'.format(dimyt0[i], style=yaxv[1])) dimxT0 = 'x' dimyT0 = 'y' if mapv is not None: pixkind = 'data' else: # No following data values dimxt0 = np.arange(len(dimxt0),dtype=np.float)/(len(dimxt0)) dimyt0 = np.arange(len(dimyt0),dtype=np.float)/(len(dimyt0)) pixkind = 'fixpixel' # No transformation # if reva is not None: # extravals, xval, yval, dimxt, dimyt, dimxl, dimyl, dimxT, dimyT = \ # transform(extravals, reva, dxv=dimxv0, dyv=dimyv0, dxt=dimxt0, dyt=dimyt0, \ # dxl=dimxl0, dyl=dimyl0, dxtit=dimxT0, dytit=dimyT0) # else: # dimxv = dimxv0 # dimyv = dimyv0 # dimxt = dimxt0 # dimyt = dimyt0 # dimxl = dimxl0 # dimyl = dimyl0 # dimxT = dimxT0 # dimyT = dimyT0 dimxv = dimxv0 dimyv = dimyv0 dimxt = dimxt0 dimyt = dimyt0 dimxl = dimxl0 dimyl = dimyl0 dimxT = dimxT0 dimyT = dimyT0 # Changing line kinds every 7 pts (end of standard colors) ptkinds=['.','x','o','*','+','8','>','D','h','p','s'] Npts = len(xval) if Npts > len(ptkinds)*7: print errormsg print ' ' + fname + ': too many',Npts,'points!!' print " enlarge 'ptkinds' list" quit(-1) N7pts = 0 if color == 'auto': ptcol = "red" else: ptcol = color dx=vlon.shape[1] dy=vlat.shape[0] plt.rc('text', usetex=True) if not mapv is None: # vlon = np.where(vlon[:] < 0., 360. + vlon[:], vlon[:]) # xvala = np.array(xval) # xvala = np.where(xvala < 0., 360. + xvala, xvala) # xval = list(xvala) map_proj=mapv.split(',')[0] map_res=mapv.split(',')[1] nlon = np.min(vlon) xlon = np.max(vlon) nlat = np.min(vlat) xlat = np.max(vlat) lon2 = vlon[dy/2,dx/2] lat2 = vlat[dy/2,dx/2] print 'lon2:', lon2, 'lat2:', lat2, 'SW pt:', nlon, ',', nlat, 'NE pt:', \ xlon, ',', xlat if map_proj == 'cyl': m = Basemap(projection=map_proj, llcrnrlon=nlon, llcrnrlat=nlat, \ urcrnrlon=xlon, urcrnrlat= xlat, resolution=map_res) elif map_proj == 'lcc': m = Basemap(projection=map_proj, lat_0=lat2, lon_0=lon2, llcrnrlon=nlon, \ llcrnrlat=nlat, urcrnrlon=xlon, urcrnrlat= xlat, resolution=map_res) else: print errormsg print ' ' + fname + ": map projecion '" + map_proj + "' not ready!!" print ' available: cyl, lcc' quit(-1) # lons, lats = np.meshgrid(vlon, vlat) # lons = np.where(lons < 0., lons + 360., lons) x,y = m(vlon,vlat) m.drawcoastlines() meridians = gen.pretty_int(nlon,xlon,5) m.drawmeridians(meridians,labels=[True,False,False,True]) parallels = gen.pretty_int(nlat,xlat,5) m.drawparallels(parallels,labels=[False,True,True,False]) else: x = vlon y = vlat # plt.xlim(0,dx-1) # plt.ylim(0,dy-1) # Extra values if extravals is not None: if len(extravals.shape) != 2: print errormsg print ' ' + fname + ': extravalues must be 2-rank !!' print ' given shape:', extravals.shape quit(-1) plt.pcolormesh(x, y, extravals, cmap=plt.get_cmap(extrapar[3]), \ vmin=extrapar[1], vmax=extrapar[2]) if extrapar[5] == 'horizontal': cbar = plt.colorbar(format=extrapar[4],orientation=extrapar[5]) # From: http://stackoverflow.com/questions/32050030/rotation-of-colorbar-tick-labels-in-matplotlib ticklabels= cbar.ax.get_xticklabels() Nticks = len(ticklabels) ticklabs = [] for itick in range(Nticks): ticklabs.append(ticklabels[itick].get_text()) cbar.ax.set_xticklabels(ticklabs,rotation=90) else: cbar = plt.colorbar(format=extrapar[4],orientation=extrapar[5]) cbar.set_label(gen.latex_text(extrapar[0]) +'('+ units_lunits(extrapar[6]) + \ ')') if labels is not None: if figk[0:8] == 'labelled': if len(figk.split(',')) != 4: print errormsg print ' ' + fname + ": 'labelled' requires three additional values !!" print " 'labelled',[txtsize],[txtcolor],[txtbckgcolor]" quit(-1) txtsize=int(figk.split(',')[1]) txtcol=figk.split(',')[2] bcktxtcol=figk.split(',')[3] if bcktxtcol != 'None': for iv in range(len(xval)): plt.annotate(labels[iv], xy=(xval[iv],yval[iv]), xycoords='data',\ fontsize=txtsize, color=txtcol, backgroundcolor=bcktxtcol, \ zorder=2) else: for iv in range(len(xval)): plt.annotate(labels[iv], xy=(xval[iv],yval[iv]), xycoords='data',\ fontsize=txtsize, color=txtcol, zorder=2) for iv in range(len(xval)): if np.mod(iv,7) == 0: N7pts = N7pts + 1 plt.plot(xval[iv],yval[iv], ptkinds[N7pts], color=txtcol, zorder=3) elif figk[0:6]== 'legend': for iv in range(len(xval)): if np.mod(iv,7) == 0: N7pts = N7pts + 1 plt.plot(xval[iv],yval[iv], ptkinds[N7pts], label=labels[iv]) plt.legend(loc=lloc, prop={'size':gsize}) else: plt.plot(xval, yval, '.', color=ptcol) graphtit = gen.latex_text(vtit.replace('|',' ')) plt.title(graphtit) output_kind(kfig, figname, ifclose) return def plot_list_points(xval, yval, varxn, varyn, vtit, figk, color, ptk, pts, labels, \ lloc, lsiz, kfig, figname, fclose): """ plotting points [x/yval]: x,y values to plot var[x/y]n: names of the x,y variables vtit= title of the graph figK= kind of figure 'legend': only points in the map with the legend with the names 'labelled',[txtsize],[txtcol]: points with the names and size, color of text color= color for the points/labels ('auto', for "red") ptk= kind of point pts= point size labels= list of labels for the points (None, no labels) lloc = localisation of the legend lsiz = font size of labels of the legend kfig= kind of figure (jpg, pdf, png) figname= name of the figure fclose= whether the figure should be close or not """ fname = 'plot_points' # Canging line kinds every 7 pts (end of standard colors) ptkinds=['.','x','o','*','+','8','>','D','h','p','s'] if color == 'auto': ptcol = "red" else: ptcol = color plt.rc('text', usetex=True) if labels is not None: for iv in range(len(xval)): # print iv,xval[iv],yval[iv],labels[iv],ptkinds[N7pts] plt.plot(xval[iv],yval[iv], ptk, markersize=pts, \ label=gen.latex_text(labels[iv])) if figk[0:8] == 'labelled': txtsize=int(figk.split(',')[1]) txtcol=figk.split(',')[2] for iv in range(len(xval)): plt.annotate(gen.latex_text(labels[iv]), xy=(xval[iv],yval[iv]), \ xycoords='data', fontsize=txtsize, color=txtcol) elif figk == 'legend': plt.legend(loc=lloc, prop={'size':lsiz}) else: plt.plot(xval, yval, ptk, markersize=pts, color=ptcol) plt.xlabel(varxn) plt.ylabel(varyn) graphtit = gen.latex_text(vtit) plt.title(graphtit) output_kind(kfig, figname, fclose) return def plot_2Dfield(varv,dimn,colorbar,vn,vx,unit,olon,olat,ifile,vtit,zvalue,time,tk, \ tkt,tobj,tvals,tind,kfig,mapv,reva): """ Adding labels and other staff to the graph varv= 2D values to plot dimn= dimension names to plot colorbar= name of the color bar to use vn,vm= minmum and maximum values to plot unit= units of the variable olon,olat= longitude, latitude objects ifile= name of the input file vtit= title of the variable zvalue= value on the z axis time= value on the time axis tk= kind of time (WRF) tkt= kind of time taken tobj= tim object tvals= values of the time variable tind= time index kfig= kind of figure (jpg, pdf, png) mapv= map characteristics: [proj],[res] see full documentation: http://matplotlib.org/basemap/ [proj]: projection * 'cyl', cilindric [res]: resolution: * 'c', crude * 'l', low * 'i', intermediate * 'h', high * 'f', full reva= reverse the axes (x-->y, y-->x) """ ## import matplotlib as mpl ## mpl.use('Agg') ## import matplotlib.pyplot as plt if reva: print ' reversing the axes of the figure (x-->y, y-->x)!!' varv = np.transpose(varv) dimn0 = [] dimn0.append(dimn[1] + '') dimn0.append(dimn[0] + '') dimn = dimn0 fname = 'plot_2Dfield' dx=varv.shape[1] dy=varv.shape[0] plt.rc('text', usetex=True) # plt.rc('font', family='serif') if not mapv is None: if len(olon[:].shape) == 3: lon0 = np.where(olon[0,] < 0., 360. + olon[0,], olon[0,]) lat0 = olat[0,] elif len(olon[:].shape) == 2: lon0 = np.where(olon[:] < 0., 360. + olon[:], olon[:]) lat0 = olat[:] elif len(olon[:].shape) == 1: lon00 = np.where(olon[:] < 0., 360. + olon[:], olon[:]) lat00 = olat[:] lon0 = np.zeros( (len(lat00),len(lon00)), dtype=np.float ) lat0 = np.zeros( (len(lat00),len(lon00)), dtype=np.float ) for iy in range(len(lat00)): lon0[iy,:] = lon00 for ix in range(len(lon00)): lat0[:,ix] = lat00 map_proj=mapv.split(',')[0] map_res=mapv.split(',')[1] nlon = lon0[0,0] xlon = lon0[dy-1,dx-1] nlat = lat0[0,0] xlat = lat0[dy-1,dx-1] lon2 = lon0[dy/2,dx/2] lat2 = lat0[dy/2,dx/2] print ' lon2:', lon2, 'lat2:', lat2, 'SW pt:', nlon, ',', nlat, 'NE pt:', \ xlon, ',', xlat if map_proj == 'cyl': m = Basemap(projection=map_proj, llcrnrlon=nlon, llcrnrlat=nlat, \ urcrnrlon=xlon, urcrnrlat= xlat, resolution=map_res) elif map_proj == 'lcc': m = Basemap(projection=map_proj, lat_0=lat2, lon_0=lon2, llcrnrlon=nlon, \ llcrnrlat=nlat, urcrnrlon=xlon, urcrnrlat= xlat, resolution=map_res) if len(olon[:].shape) == 1: lons, lats = np.meshgrid(olon[:], olat[:]) else: lons = olon[0,:] lats = olat[:,0] lons = np.where(lons < 0., lons + 360., lons) x,y = m(lons,lats) plt.pcolormesh(x,y,varv, cmap=plt.get_cmap(colorbar), vmin=vn, vmax=vx) cbar = plt.colorbar() m.drawcoastlines() # if (nlon > 180. or xlon > 180.): # nlon0 = nlon # xlon0 = xlon # if (nlon > 180.): nlon0 = nlon - 360. # if (xlon > 180.): xlon0 = xlon - 360. # meridians = gen.pretty_int(nlon0,xlon0,5) # meridians = np.where(meridians < 0., meridians + 360., meridians) # else: # meridians = gen.pretty_int(nlon,xlon,5) meridians = gen.pretty_int(nlon,xlon,5) m.drawmeridians(meridians,labels=[True,False,False,True]) parallels = gen.pretty_int(nlat,xlat,5) m.drawparallels(parallels,labels=[False,True,True,False]) else: plt.xlim(0,dx-1) plt.ylim(0,dy-1) plt.pcolormesh(varv, cmap=plt.get_cmap(colorbar), vmin=vn, vmax=vx) cbar = plt.colorbar() plt.xlabel(dimn[1].replace('_','\_')) plt.ylabel(dimn[0].replace('_','\_')) # set the limits of the plot to the limits of the data # plt.axis([x.min(), x.max(), y.min(), y.max()]) # plt.plot(varv) cbar.set_label(unit) figname = ifile.replace('.','_') + '_' + vtit graphtit = vtit.replace('_','\_').replace('&','\&') if zvalue != 'null': graphtit = graphtit + ' at z= ' + zvalue figname = figname + '_z' + zvalue if tkt == 'tstep': graphtit = graphtit + ' at time-step= ' + time.split(',')[1] figname = figname + '_t' + time.split(',')[1].zfill(4) elif tkt == 'CFdate': graphtit = graphtit + ' at ' + tobj.strfmt("%Y%m%d%H%M%S") figname = figname + '_t' + tobj.strfmt("%Y%m%d%H%M%S") if tk == 'WRF': # datev = str(timevals[timeind][0:9]) datev = tvals[tind][0] + tvals[tind][1] + tvals[tind][2] + \ timevals[timeind][3] + timevals[timeind][4] + timevals[timeind][5] + \ timevals[timeind][6] + timevals[timeind][7] + timevals[timeind][8] + \ timevals[timeind][9] # timev = str(timevals[timeind][11:18]) timev = timevals[timeind][11] + timevals[timeind][12] + \ timevals[timeind][13] + timevals[timeind][14] + timevals[timeind][15] + \ timevals[timeind][16] + timevals[timeind][17] + timevals[timeind][18] graphtit = vtit.replace('_','\_') + ' (' + datev + ' ' + timev + ')' plt.title(graphtit) output_kind(kfig, figname, True) return def plot_2Dfield_easy(varv,dimxv,dimyv,dimn,colorbar,vn,vx,unit,ifile,vtit,kfig,reva): """ Adding labels and other staff to the graph varv= 2D values to plot dim[x/y]v = values at the axes of x and y dimn= dimension names to plot colorbar= name of the color bar to use vn,vm= minmum and maximum values to plot unit= units of the variable ifile= name of the input file vtit= title of the variable kfig= kind of figure (jpg, pdf, png) reva= reverse the axes (x-->y, y-->x) """ ## import matplotlib as mpl ## mpl.use('Agg') ## import matplotlib.pyplot as plt fname = 'plot_2Dfield' if reva: print ' reversing the axes of the figure (x-->y, y-->x)!!' varv = np.transpose(varv) dimn0 = [] dimn0.append(dimn[1] + '') dimn0.append(dimn[0] + '') dimn = dimn0 if len(dimyv.shape) == 2: x = np.transpose(dimyv) else: if len(dimxv.shape) == 2: ddx = len(dimyv) ddy = dimxv.shape[1] else: ddx = len(dimyv) ddy = len(dimxv) x = np.zeros((ddy,ddx), dtype=np.float) for j in range(ddy): x[j,:] = dimyv if len(dimxv.shape) == 2: y = np.transpose(dimxv) else: if len(dimyv.shape) == 2: ddx = dimyv.shape[0] ddy = len(dimxv) else: ddx = len(dimyv) ddy = len(dimxv) y = np.zeros((ddy,ddx), dtype=np.float) for i in range(ddx): y[:,i] = dimxv else: if len(dimxv.shape) == 2: x = dimxv else: x = np.zeros((len(dimyv),len(dimxv)), dtype=np.float) for j in range(len(dimyv)): x[j,:] = dimxv if len(dimyv.shape) == 2: y = dimyv else: y = np.zeros((len(dimyv),len(dimxv)), dtype=np.float) for i in range(len(dimxv)): x[:,i] = dimyv dx=varv.shape[1] dy=varv.shape[0] plt.rc('text', usetex=True) plt.xlim(0,dx-1) plt.ylim(0,dy-1) plt.pcolormesh(x, y, varv, cmap=plt.get_cmap(colorbar), vmin=vn, vmax=vx) # plt.pcolormesh(varv, cmap=plt.get_cmap(colorbar), vmin=vn, vmax=vx) cbar = plt.colorbar() plt.xlabel(dimn[1].replace('_','\_')) plt.ylabel(dimn[0].replace('_','\_')) # set the limits of the plot to the limits of the data plt.axis([x.min(), x.max(), y.min(), y.max()]) # if varv.shape[1] / varv.shape[0] > 10: # plt.axes().set_aspect(0.001) # else: # plt.axes().set_aspect(np.float(varv.shape[0])/np.float(varv.shape[1])) cbar.set_label(unit) figname = ifile.replace('.','_') + '_' + vtit graphtit = vtit.replace('_','\_').replace('&','\&') plt.title(graphtit) output_kind(kfig, figname, True) return def plot_Trajectories(lonval, latval, timeval, plotk, linesn, trjlt, trjlc, trjlw, \ trjpt, trjps, olon, olat, obstrjv, lonlatLims, gtit, kfig, mapv, obsname, lleg, \ sleg, close): """ plotting Trajectories [lon/latval]= lon,lat values to plot (as list of vectors) timeval= time values to plot (if required, as list of vectors) plotk= kind of plot: 'spaghetti', 'spaghetti_date' linesn= name of the lines trjlt= ',' list of type of lines for each trajectory (single value for all trajetories with the same) trjlc= ',' list of color of lines for each trajectory (single value for all trajetories with the same) trjlw= ',' list of width of lines for each trajectory (single value for all trajetories with the same) trjpt= ',' list of type of points for each trajectory (single value for all trajetories with the same) trjps= ',' list of size of points for each trajectory (single value for all trajetories with the same) o[lon/lat]= object with the longitudes and the latitudes of the map to plot obstrjv: values for the line of the observations/trajectory lonlatLims: limits of longitudes and latitudes [lonmin, latmin, lonmax, latmax] gtit= title of the graph kfig= kind of figure (jpg, pdf, png) mapv= map characteristics: [proj],[res] see full documentation: http://matplotlib.org/basemap/ [proj]: projection * 'cyl', cilindric * 'lcc', lambert conformal [res]: resolution: * 'c', crude * 'l', low * 'i', intermediate * 'h', high * 'f', full obsname= name of the observations in graph (can be None for without). Observational trajectory would be the last one lleg= location of the legend sleg= fontsize of the legend close= whether figure should be closed or not """ fname = 'plot_Trajectories' if lonval == 'h': print fname + '_____________________________________________________________' print plot_Trajectories.__doc__ quit() Ntraj = len(lonval) if obsname is not None: Ntraj = Ntraj - 1 if Ntraj != len(linesn): print errormsg print ' '+fname+': number of trajectories:', Ntraj, 'and number of labels:',\ len(linesn), 'differ !!' print ' provided labels:', linesn quit(-1) cols, lins, pts, lws, pss = ColorsLinesPointsStyles(Ntraj, trjlc, trjlt, trjpt, \ trjlw, trjps, 'all') plt.rc('text', usetex=True) if not mapv is None: if len(olon[:].shape) == 3: # lon0 = np.where(olon[0,] < 0., 360. + olon[0,], olon[0,]) lon0 = olon[0,] lat0 = olat[0,] elif len(olon[:].shape) == 2: # lon0 = np.where(olon[:] < 0., 360. + olon[:], olon[:]) lon0 = olon[:] lat0 = olat[:] elif len(olon[:].shape) == 1: # lon00 = np.where(olon[:] < 0., 360. + olon[:], olon[:]) lon00 = olon[:] lat00 = olat[:] lon0 = np.zeros( (len(lat00),len(lon00)), dtype=np.float ) lat0 = np.zeros( (len(lat00),len(lon00)), dtype=np.float ) for iy in range(len(lat00)): lon0[iy,:] = lon00 for ix in range(len(lon00)): lat0[:,ix] = lat00 map_proj=mapv.split(',')[0] map_res=mapv.split(',')[1] dx = lon0.shape[1] dy = lon0.shape[0] nlon = np.min(lon0) xlon = np.max(lon0) nlat = np.min(lat0) xlat = np.max(lat0) lon2 = lon0[dy/2,dx/2] lat2 = lat0[dy/2,dx/2] if lonlatLims is not None: plt.xlim(lonlatLims[0], lonlatLims[2]) plt.ylim(lonlatLims[1], lonlatLims[3]) if map_proj == 'cyl': nlon = lonlatLims[0] nlat = lonlatLims[1] xlon = lonlatLims[2] xlat = lonlatLims[3] print 'lon2:', lon2, 'lat2:', lat2, 'SW pt:', nlon, ',', nlat, 'NE pt:', \ xlon, ',', xlat if map_proj == 'cyl': m = Basemap(projection=map_proj, llcrnrlon=nlon, llcrnrlat=nlat, \ urcrnrlon=xlon, urcrnrlat= xlat, resolution=map_res) elif map_proj == 'lcc': m = Basemap(projection=map_proj, lat_0=lat2, lon_0=lon2, llcrnrlon=nlon, \ llcrnrlat=nlat, urcrnrlon=xlon, urcrnrlat= xlat, resolution=map_res) if len(olon.shape) == 3: # lons, lats = np.meshgrid(olon[0,:,:], olat[0,:,:]) lons = olon[0,:,:] lats = olat[0,:,:] elif len(olon.shape) == 2: # lons, lats = np.meshgrid(olon[:,:], olat[:,:]) lons = olon[:,:] lats = olat[:,:] else: dx = olon.shape dy = olat.shape # print errormsg # print ' ' + fname + ': shapes of lon/lat objects', olon.shape, \ # 'not ready!!!' m.drawcoastlines() meridians = gen.pretty_int(nlon,xlon,5) m.drawmeridians(meridians,labels=[True,False,False,True]) parallels = gen.pretty_int(nlat,xlat,5) m.drawparallels(parallels,labels=[False,True,True,False]) plt.xlabel('W-E') plt.ylabel('S-N') else: if len(olon.shape) == 3: dx = olon.shape[2] dy = olon.shape[1] elif len(olon.shape) == 2: dx = olon.shape[1] dy = olon.shape[0] else: dx = olon.shape dy = olat.shape # print errormsg # print ' ' + fname + ': shapes of lon/lat objects', olon.shape, \ # 'not ready!!!' if lonlatLims is not None: plt.xlim(lonlatLims[0], lonlatLims[2]) plt.ylim(lonlatLims[1], lonlatLims[3]) else: plt.xlim(np.min(olon[:]),np.max(olon[:])) plt.ylim(np.min(olat[:]),np.max(olat[:])) plt.xlabel('x-axis') plt.ylabel('y-axis') if plotk[0] == 'spaghetti': for il in range(Ntraj): plt.plot(lonval[il], latval[il], lins[il], marker=pts[il], \ color=cols[il], label=gen.latex_text(linesn[il]), linewidth=lws[il], \ markersize=pss[il]) elif plotk[0] == 'spaghetti_date': ofs = np.array(plotk[9:11], dtype=int) for il in range(Ntraj): plt.plot(lonval[il], latval[il], lins[il], marker=pts[il], \ color=cols[il], label=gen.latex_text(linesn[il]), linewidth=lws[il], \ markersize=pss[il]) lvals = lonval[il] Lvals = latval[il] tvals = timeval[il] Nvals = len(tvals) for it in range(0,Nvals,int(plotk[8])): if tvals[it] is not None: plt.annotate(gen.latex_text(tvals[it].strftime(plotk[6])), \ xy=(lvals[it],Lvals[it]), color=cols[il], fontsize=plotk[7], \ horizontalalignment="center", xytext=(ofs[0],ofs[1]), \ textcoords='offset pixels') if obsname is not None: il = Ntraj if plotk[0] == 'spaghetti': plt.plot(lonval[il], latval[il], linestyle=obstrjv[0], \ marker=obstrjv[3], color=obstrjv[1], label=gen.latex_text(obsname), \ linewidth=obstrjv[2], markersize=obstrjv[4]) elif plotk[0] == 'spaghetti_date': plt.plot(lonval[il], latval[il], linestyle=obstrjv[0], \ marker=obstrjv[3], color=obstrjv[1], label=gen.latex_text(obsname), \ linewidth=obstrjv[2], markersize=obstrjv[4]) lvals = lonval[il] Lvals = latval[il] tvals = timeval[il] Nvals = len(tvals) for it in range(0,Nvals,int(plotk[8])): if lvals[it] is not None and tvals[it] is not None: plt.annotate(gen.latex_text(tvals[it].strftime(plotk[6])), \ xy=(lvals[it],Lvals[it]), color=obstrjv[1], fontsize=plotk[7], \ horizontalalignment="center", xytext=(ofs[0],ofs[1]), \ textcoords='offset pixels') if plotk[0] == 'spaghetti_date': Tlab = gen.timefmt_timelab(plotk[6]) plt.annotate('time labels as ' + gen.latex_text(Tlab), xy=(0.75,0.05), \ color='k', xycoords='figure fraction') plt.title(gtit) plt.legend(loc=lleg, prop={'size':sleg}) figname = 'trajectories' output_kind(kfig, figname, close) return def plot_topo_geogrid(varv, olon, olat, mint, maxt, lonlatLims, gtit, kfig, mapv, \ closeif): """ plotting geo_em.d[nn].nc topography from WPS files plot_topo_geogrid(domf, mint, maxt, gtit, kfig, mapv) varv= topography values o[lon/lat]= longitude and latitude objects [min/max]t: minimum and maximum values of topography to draw lonlatLims: limits of longitudes and latitudes [lonmin, latmin, lonmax, latmax] gtit= title of the graph kfig= kind of figure (jpg, pdf, png) mapv= map characteristics: [proj],[res] see full documentation: http://matplotlib.org/basemap/ [proj]: projection * 'cyl', cilindric * 'lcc', lamvbert conformal [res]: resolution: * 'c', crude * 'l', low * 'i', intermediate * 'h', high * 'f', full closeif= Boolean value if the figure has to be closed """ fname = 'plot_topo_geogrid' if varv == 'h': print fname + '_____________________________________________________________' print plot_topo_geogrid.__doc__ quit() dx=varv.shape[1] dy=varv.shape[0] plt.rc('text', usetex=True) # plt.rc('font', family='serif') if not mapv is None: if len(olon[:].shape) == 3: lon0 = olon[0,] lat0 = olat[0,] elif len(olon[:].shape) == 2: lon0 = olon[:] lat0 = olat[:] elif len(olon[:].shape) == 1: lon00 = olon[:] lat00 = olat[:] lon0 = np.zeros( (len(lat00),len(lon00)), dtype=np.float ) lat0 = np.zeros( (len(lat00),len(lon00)), dtype=np.float ) for iy in range(len(lat00)): lon0[iy,:] = lon00 for ix in range(len(lon00)): lat0[:,ix] = lat00 map_proj=mapv.split(',')[0] map_res=mapv.split(',')[1] dx = lon0.shape[1] dy = lon0.shape[0] if lonlatLims is not None: print ' ' + fname + ': cutting the domain to plot !!!!' print ' limits: W-E', lonlatLims[0], lonlatLims[2] print ' limits: N-S', lonlatLims[1], lonlatLims[3] nlon = lonlatLims[0] xlon = lonlatLims[2] nlat = lonlatLims[1] xlat = lonlatLims[3] if map_proj == 'lcc': lon2 = (lonlatLims[0] + lonlatLims[2])/2. lat2 = (lonlatLims[1] + lonlatLims[3])/2. else: nlon = np.min(lon0) xlon = np.max(lon0) nlat = np.min(lat0) xlat = np.max(lat0) lon2 = lon0[dy/2,dx/2] lat2 = lat0[dy/2,dx/2] plt.xlim(nlon, xlon) plt.ylim(nlat, xlat) print 'lon2:', lon2, 'lat2:', lat2, 'SW pt:', nlon, ',', nlat, 'NE pt:', \ xlon, ',', xlat if map_proj == 'cyl': m = Basemap(projection=map_proj, llcrnrlon=nlon, llcrnrlat=nlat, \ urcrnrlon=xlon, urcrnrlat= xlat, resolution=map_res) elif map_proj == 'lcc': m = Basemap(projection=map_proj, lat_0=lat2, lon_0=lon2, llcrnrlon=nlon, \ llcrnrlat=nlat, urcrnrlon=xlon, urcrnrlat= xlat, resolution=map_res) else: print errormsg print ' ' + fname + ": map projection '" + map_proj + "' not ready !!" quit(-1) if len(olon[:].shape) == 1: lons, lats = np.meshgrid(olon[:], olat[:]) else: if len(olon[:].shape) == 3: lons = olon[0,:,:] lats = olat[0,:,:] else: lons = olon[:] lats = olat[:] x,y = m(lons,lats) plt.pcolormesh(x,y,varv, cmap=plt.get_cmap('terrain'), vmin=mint, vmax=maxt) cbar = plt.colorbar() m.drawcoastlines() meridians = gen.pretty_int(nlon,xlon,5) m.drawmeridians(meridians,labels=[True,False,False,True]) parallels = gen.pretty_int(nlat,xlat,5) m.drawparallels(parallels,labels=[False,True,True,False]) plt.xlabel('W-E') plt.ylabel('S-N') else: print emsg print ' ' + fname + ': A projection parameter is needed None given !!' quit(-1) figname = 'domain' graphtit = gen.latex_text(gtit) cbar.set_label('height ($m$)') plt.title(graphtit) output_kind(kfig, figname, closeif) return def plot_topo_geogrid_boxes(varv, boxesX, boxesY, boxlabels, olon, olat, mint, maxt, \ lonlatLims, gtit, kfig, mapv, gloc, gsiz, closeif): """ plotting geo_em.d[nn].nc topography from WPS files plot_topo_geogrid(domf, mint, maxt, gtit, kfig, mapv) varv= topography values boxesX/Y= 4-line sets to draw the boxes boxlabels= labels for the legend of the boxes o[lon/lat]= longitude and latitude objects [min/max]t: minimum and maximum values of topography to draw lonlatLims: limits of longitudes and latitudes [lonmin, latmin, lonmax, latmax] gtit= title of the graph kfig= kind of figure (jpg, pdf, png) mapv= map characteristics: [proj],[res] see full documentation: http://matplotlib.org/basemap/ [proj]: projection * 'cyl', cilindric * 'lcc', lamvbert conformal [res]: resolution: * 'c', crude * 'l', low * 'i', intermediate * 'h', high * 'f', full gloc= location of the legend (0, autmoatic) 1: 'upper right', 2: 'upper left', 3: 'lower left', 4: 'lower right', 5: 'right', 6: 'center left', 7: 'center right', 8: 'lower center', 9: 'upper center', 10: 'center' gsiz= fontsize of the legend closeif= Boolean value if the figure has to be closed """ fname = 'plot_topo_geogrid' if type(varv) == type('S') and varv == 'h': print fname + '_____________________________________________________________' print plot_topo_geogrid.__doc__ quit() #cols = color_lines(len(boxlabels)) cols = colorsauto dx=varv.shape[1] dy=varv.shape[0] plt.rc('text', usetex=True) # plt.rc('font', family='serif') if not mapv is None: if len(olon[:].shape) == 3: lon0 = olon[0,] lat0 = olat[0,] elif len(olon[:].shape) == 2: lon0 = olon[:] lat0 = olat[:] elif len(olon[:].shape) == 1: lon00 = olon[:] lat00 = olat[:] lon0 = np.zeros( (len(lat00),len(lon00)), dtype=np.float ) lat0 = np.zeros( (len(lat00),len(lon00)), dtype=np.float ) for iy in range(len(lat00)): lon0[iy,:] = lon00 for ix in range(len(lon00)): lat0[:,ix] = lat00 map_proj=mapv.split(',')[0] map_res=mapv.split(',')[1] dx = lon0.shape[1] dy = lon0.shape[0] if lonlatLims is not None: print ' ' + fname + ': cutting the domain to plot !!!!' print ' limits: W-E', lonlatLims[0], lonlatLims[2] print ' limits: N-S', lonlatLims[1], lonlatLims[3] nlon = lonlatLims[0] xlon = lonlatLims[2] nlat = lonlatLims[1] xlat = lonlatLims[3] if map_proj == 'lcc': lon2 = (lonlatLims[0] + lonlatLims[2])/2. lat2 = (lonlatLims[1] + lonlatLims[3])/2. else: nlon = np.min(lon0) xlon = np.max(lon0) nlat = np.min(lat0) xlat = np.max(lat0) lon2 = lon0[dy/2,dx/2] lat2 = lat0[dy/2,dx/2] plt.xlim(nlon, xlon) plt.ylim(nlat, xlat) print 'lon2:', lon2, 'lat2:', lat2, 'SW pt:', nlon, ',', nlat, 'NE pt:', \ xlon, ',', xlat if map_proj == 'cyl': m = Basemap(projection=map_proj, llcrnrlon=nlon, llcrnrlat=nlat, \ urcrnrlon=xlon, urcrnrlat= xlat, resolution=map_res) elif map_proj == 'lcc': m = Basemap(projection=map_proj, lat_0=lat2, lon_0=lon2, llcrnrlon=nlon, \ llcrnrlat=nlat, urcrnrlon=xlon, urcrnrlat= xlat, resolution=map_res) else: print errormsg print ' ' + fname + ": projection '" + map_proj + "' does not exist!!" print ' existing ones: cyl, lcc' quit(-1) if len(olon[:].shape) == 1: lons, lats = np.meshgrid(olon[:], olat[:]) else: if len(olon[:].shape) == 3: lons = olon[0,:,:] lats = olat[0,:,:] else: lons = olon[:] lats = olat[:] x,y = m(lons,lats) plt.pcolormesh(x,y,varv, cmap=plt.get_cmap('terrain'), vmin=mint, vmax=maxt) cbar = plt.colorbar() Nboxes = len(boxesX)/4 for ibox in range(Nboxes): plt.plot(boxesX[ibox*4], boxesY[ibox*4], linestyle='-', linewidth=3, \ label=gen.latex_text(boxlabels[ibox].replace('!',' ')), color=cols[ibox]) plt.plot(boxesX[ibox*4+1], boxesY[ibox*4+1], linestyle='-', linewidth=3, \ color=cols[ibox]) plt.plot(boxesX[ibox*4+2], boxesY[ibox*4+2], linestyle='-', linewidth=3, \ color=cols[ibox]) plt.plot(boxesX[ibox*4+3], boxesY[ibox*4+3], linestyle='-', linewidth=3, \ color=cols[ibox]) m.drawcoastlines() meridians = gen.pretty_int(nlon,xlon,5) m.drawmeridians(meridians,labels=[True,False,False,True]) parallels = gen.pretty_int(nlat,xlat,5) m.drawparallels(parallels,labels=[False,True,True,False]) plt.xlabel('W-E') plt.ylabel('S-N') else: print emsg print ' ' + fname + ': A projection parameter is needed None given !!' quit(-1) figname = 'domain_boxes' graphtit = gen.latex_text(gtit) cbar.set_label('height ($m$)') plt.title(graphtit) plt.legend(loc=gloc, prop={'size':gsiz}) output_kind(kfig, figname, closeif) return def plot_2D_shadow(varsv, vnames, dimxv, dimyv, dimxu, dimyu, xaxv, yaxv, dimn, \ cbarv, vs, uts, vtit, kfig, reva, mapv, ifclose): """ Plot of a 2D field with shadow varsv= 2D values to plot with shading vnames= variable names for the figure dim[x/y]v = values at the axes of x and y dim[x/y]u = units at the axes of x and y xaxv= list with the x-axis paramteres [style, format, number and orientation] yaxv= list with the y-axis paramteres [style, format, number and orientation] dimn= dimension names to plot cbarv= list with the parameters of the color bar [colorbar, cbarfmt, cbaror] colorbar: name of the color bar to use cbarfmt: format of the numbers in the colorbar cbaror: orientation of the colorbar vs= minmum and maximum values to plot in shadow or: 'Srange': for full range 'Saroundmean@val': for mean-xtrm,mean+xtrm where xtrm = np.min(mean-min@val,max@val-mean) 'Saroundminmax@val': for min*val,max*val 'Saroundpercentile@val': for median-xtrm,median+xtrm where xtrm = np.min(median-percentile_(val), percentile_(100-val)-median) 'Smean@val': for -xtrm,xtrm where xtrm = np.min(mean-min*@val,max*@val-mean) 'Smedian@val': for -xtrm,xtrm where xtrm = np.min(median-min@val,max@val-median) 'Spercentile@val': for -xtrm,xtrm where xtrm = np.min(median-percentile_(val), percentile_(100-val)-median) uts= units of the variable to shadow vtit= title of the variable kfig= kind of figure (jpg, pdf, png) reva= ('|' for combination) * 'transpose': reverse the axes (x-->y, y-->x) * 'flip'@[x/y]: flip the axis x or y mapv= map characteristics: [proj],[res] see full documentation: http://matplotlib.org/basemap/ [proj]: projection * 'cyl', cilindric * 'lcc', lambert conformal [res]: resolution: * 'c', crude * 'l', low * 'i', intermediate * 'h', high * 'f', full ifclose= boolean value whether figure should be close (finish) or not """ ## import matplotlib as mpl ## mpl.use('Agg') ## import matplotlib.pyplot as plt fname = 'plot_2D_shadow' # print dimyv[73,21] # dimyv[73,21] = -dimyv[73,21] # print 'Lluis dimsv: ',np.min(dimxv), np.max(dimxv), ':', np.min(dimyv), np.max(dimyv) if type(varsv) == type('S') and varsv == 'h': print fname + '_____________________________________________________________' print plot_2D_shadow.__doc__ quit() if len(varsv.shape) != 2: print errormsg print ' ' + fname + ': wrong variable shadow rank:', varsv.shape, \ 'is has to be 2D!!' quit(-1) # Getting the right lon values for plotting if mapv is not None: dimxv = np.where(dimxv > 180., dimxv-360., dimxv) # Axis ticks # Usually axis > x must be the lon, thus... dimxv0 = dimxv.copy() dimyv0 = dimyv.copy() dxn = dimxv.min() dxx = dimxv.max() dyn = dimyv.min() dyx = dimyv.max() if xaxv[0] == 'pretty': dimxt0 = np.array(gen.pretty_int(dxn,dxx,xaxv[2])) elif xaxv[0] == 'Nfix': dimxt0 = np.arange(dxn,dxx,(dxx-dxn)/(1.*xaxv[2])) elif xaxv[0] == 'Vfix': dimxt0 = np.arange(0,dxx,xaxv[2]) if yaxv[0] == 'pretty': dimyt0 = np.array(gen.pretty_int(dyn,dyx,yaxv[2])) elif yaxv[0] == 'Nfix': dimyt0 = np.arange(dyn,dyx,(dyx-dyn)/(1.*yaxv[2])) elif yaxv[0] == 'Vfix': dimyt0 = np.arange(0,dyx,yaxv[2]) dimxl0 = [] for i in range(len(dimxt0)): dimxl0.append('{:{style}}'.format(dimxt0[i], style=xaxv[1])) dimyl0 = [] for i in range(len(dimyt0)): dimyl0.append('{:{style}}'.format(dimyt0[i], style=yaxv[1])) dimxT0 = variables_values(dimn[0])[0] + ' (' + units_lunits(dimxu) + ')' dimyT0 = variables_values(dimn[1])[0] + ' (' + units_lunits(dimyu) + ')' if mapv is not None: pixkind = 'data' else: # No following data values dimxt0 = np.arange(len(dimxt0),dtype=np.float)/(len(dimxt0)) dimyt0 = np.arange(len(dimyt0),dtype=np.float)/(len(dimyt0)) pixkind = 'fixpixel' if reva is not None: varsv, dimxv, dimyv, dimxt, dimyt, dimxl, dimyl, dimxT, dimyT = \ transform(varsv, reva, dxv=dimxv0, dyv=dimyv0, dxt=dimxt0, dyt=dimyt0, \ dxl=dimxl0, dyl=dimyl0, dxtit=dimxT0, dytit=dimyT0) else: dimxv = dimxv0 dimyv = dimyv0 dimxt = dimxt0 dimyt = dimyt0 dimxl = dimxl0 dimyl = dimyl0 dimxT = dimxT0 dimyT = dimyT0 if len(dimxv[:].shape) == 3: xdims = '1,2' elif len(dimxv[:].shape) == 2: xdims = '0,1' elif len(dimxv[:].shape) == 1: xdims = '0' if len(dimyv[:].shape) == 3: ydims = '1,2' elif len(dimyv[:].shape) == 2: ydims = '0,1' elif len(dimyv[:].shape) == 1: ydims = '0' # lon0 = dimxv # lat0 = dimyv lon0, lat0 = dxdy_lonlat(dimxv,dimyv, xdims, ydims) if not mapv is None: map_proj=mapv.split(',')[0] map_res=mapv.split(',')[1] dx = lon0.shape[1] dy = lat0.shape[0] # nlon = lon0[0,0] # xlon = lon0[dy-1,dx-1] # nlat = lat0[0,0] # xlat = lat0[dy-1,dx-1] nlon = np.min(lon0) xlon = np.max(lon0) nlat = np.min(lat0) xlat = np.max(lat0) # Thats too much! :) # if lonlatLims is not None: # print ' ' + fname + ': cutting the domain to plot !!!!' # plt.xlim(lonlatLims[0], lonlatLims[2]) # plt.ylim(lonlatLims[1], lonlatLims[3]) # print ' limits: W-E', lonlatLims[0], lonlatLims[2] # print ' limits: N-S', lonlatLims[1], lonlatLims[3] # if map_proj == 'cyl': # nlon = lonlatLims[0] # nlat = lonlatLims[1] # xlon = lonlatLims[2] # xlat = lonlatLims[3] # elif map_proj == 'lcc': # lon2 = (lonlatLims[0] + lonlatLims[2])/2. # lat2 = (lonlatLims[1] + lonlatLims[3])/2. # nlon = lonlatLims[0] # xlon = lonlatLims[2] # nlat = lonlatLims[1] # xlat = lonlatLims[3] lon2 = lon0[dy/2,dx/2] lat2 = lat0[dy/2,dx/2] print 'lon2:', lon2, 'lat2:', lat2, 'SW pt:', nlon, ',', nlat, 'NE pt:', \ xlon, ',', xlat if map_proj == 'cyl': m = Basemap(projection=map_proj, llcrnrlon=nlon, llcrnrlat=nlat, \ urcrnrlon=xlon, urcrnrlat= xlat, resolution=map_res) elif map_proj == 'lcc': m = Basemap(projection=map_proj, lat_0=lat2, lon_0=lon2, llcrnrlon=nlon, \ llcrnrlat=nlat, urcrnrlon=xlon, urcrnrlat= xlat, resolution=map_res) else: print errormsg print ' ' + fname + ": map projection '" + map_proj + "' not defined!!!" print ' available: cyl, lcc' quit(-1) x,y = m(lon0,lat0) else: # No following data values #x = dimxv #y = dimyv x = (dimxv-np.min(dimxv))/(np.max(dimxv) - np.min(dimxv)) y = (dimyv-np.min(dimyv))/(np.max(dimyv) - np.min(dimyv)) # Changing limits of the colors vsend = graphic_range(vs,varsv) plt.rc('text', usetex=True) plt.pcolormesh(x, y, varsv, cmap=plt.get_cmap(cbarv[0]), vmin=vsend[0], vmax=vsend[1]) if cbarv[2] == 'horizontal': cbar = plt.colorbar(format=cbarv[1],orientation=cbarv[2]) # From: http://stackoverflow.com/questions/32050030/rotation-of-colorbar-tick-labels-in-matplotlib ticklabels= cbar.ax.get_xticklabels() Nticks = len(ticklabels) ticklabs = [] for itick in range(Nticks): ticklabs.append(ticklabels[itick].get_text()) cbar.ax.set_xticklabels(ticklabs,rotation=90) else: cbar = plt.colorbar(format=cbarv[1],orientation=cbarv[2]) if not mapv is None: if cbarv[0] == 'gist_gray': m.drawcoastlines(color="red") else: m.drawcoastlines() meridians = gen.pretty_int(nlon,xlon,xaxv[2]) m.drawmeridians(meridians,labels=[True,False,False,True]) parallels = gen.pretty_int(nlat,xlat,yaxv[2]) m.drawparallels(parallels,labels=[False,True,True,False]) plt.xlabel('W-E') plt.ylabel('S-N') else: plt.xlabel(dimxT) plt.ylabel(dimyT) # Using output from transform # print 'x min:', x.min(),'max:',x.max() # print 'y min:', y.min(),'max:',y.max() # txpos = gen.pretty_int(x.min(),x.max(),5) # typos = gen.pretty_int(y.min(),y.max(),5) # txlabels = list(txpos) # for i in range(len(txlabels)): txlabels[i] = '{:6g}'.format(txlabels[i]) # tylabels = list(typos) # for i in range(len(tylabels)): tylabels[i] = '{:6g}'.format(tylabels[i]) plt.axis([x.min(), x.max(), y.min(), y.max()]) if mapv is None: # plt.xticks(txpos, txlabels) # plt.yticks(typos, tylabels) plt.xticks(dimxt, dimxl, rotation=xaxv[3]) plt.yticks(dimyt, dimyl, rotation=yaxv[3]) # units labels cbar.set_label(gen.latex_text(vnames) + ' (' + units_lunits(uts) + ')') figname = '2Dfields_shadow' #graphtit = gen.latex_text(vtit) plt.title(gen.latex_text(vtit)) output_kind(kfig, figname, ifclose) return #Nvals=50 #vals1 = np.zeros((Nvals,Nvals), dtype= np.float) #for j in range(Nvals): # for i in range(Nvals): # vals1[j,i]=np.sqrt((j-Nvals/2)**2. + (i-Nvals/2)**2.) #plot_2D_shadow(vals1, 'var1', np.arange(50)*1., np.arange(50)*1., 'ms-1', \ # 'm', ['lat','lon'], 'rainbow', [0, Nvals], 'ms-1', 'test var1', 'pdf', 'None', \ # None, True) #quit() def plot_2D_shadow_time(varsv, vnames, dimvv, dimtv, dimvu, dimn, vaxv, cbarv, \ vs, uts, xpixk, ypixk, vtit, kfig, reva, taxis, tpos, tlabs, ifclose): """ Plotting a 2D field with one of the axes being time varsv= 2D values to plot with shading vnames= shading variable name for the figure dimvv= values at the axis of values dimtv= values at the axis of time dimvu= units at the axes of values dimn= dimension names to plot vaxv= list with the non-temporal axis paramteres [style, format, number and orientation] cbarv= list with the parameters of the color bar [colorbar, cbarfmt, cbaror] colorbar: name of the color bar to use cbarfmt: format of the numbers in the colorbar cbaror: orientation of the colorbar vs= minmum and maximum values to plot in shadow or: 'Srange': for full range 'Saroundmean@val': for mean-xtrm,mean+xtrm where xtrm = np.min(mean-min@val,max@val-mean) 'Saroundminmax@val': for min*val,max*val 'Saroundpercentile@val': for median-xtrm,median+xtrm where xtrm = np.min(median-percentile_(val), percentile_(100-val)-median) 'Smean@val': for -xtrm,xtrm where xtrm = np.min(mean-min*@val,max*@val-mean) 'Smedian@val': for -xtrm,xtrm where xtrm = np.min(median-min@val,max@val-median) 'Spercentile@val': for -xtrm,xtrm where xtrm = np.min(median-percentile_(val), percentile_(100-val)-median) uts= units of the variable to shadow [x/ypixk]= kind of grid-pixel for the figure 'data': size pixel along the given axis change according to the values along the axis 'fixpixel': size pixel along the given axis does not change vtit= title of the figure kfig= kind of figure (jpg, pdf, png) reva= '|' for transformations to apply * 'transpose': reverse the axes (x-->y, y-->x) * 'flip'@[x/y]: flip the axis x or y taxis= Which is the time-axis tpos= positions of the time ticks tlabs= labels of the time ticks ifclose= boolean value whether figure should be close (finish) or not """ fname = 'plot_2D_shadow_time' if type(varsv) == type('S') and varsv == 'h': print fname + '_____________________________________________________________' print plot_2D_shadow_time.__doc__ quit() if len(varsv.shape) != 2: print errormsg print ' ' + fname + ': wrong variable shadow rank:', varsv.shape, \ 'is has to be 2D!!' quit(-1) # Definning ticks labels if taxis == 'x': dimxv0 = dimtv.copy() dimyv0 = dimvv.copy() dxn = dimtv.min() dxx = dimtv.max() dyn = dimvv.min() dyx = dimvv.max() dimxt0 = tpos dimxl0 = tlabs dimxT0 = 'cf time' if vaxv[0] == 'pretty': dimyt0 = np.array(gen.pretty_int(dyn,dyx+(dyx-dyn)/vaxv[2],vaxv[2])) elif vaxv[0] == 'Nfix': dimyt0 = np.arange(dyn,dyx,(dyx-dyn)/(1.*vaxv[2])) elif vaxv[0] == 'Vfix': dimyt0 = np.arange(0,dyx,vaxv[2]) dimyl0 = [] for i in range(len(dimyt0)): dimyl0.append('{:{style}}'.format(dimyt0[i], \ style=vaxv[1])) dimyT0 = gen.latex_text(variables_values(dimn[1])[0]) + ' (' + \ units_lunits(dimvu) + ')' # No following data values #dimyt0 = np.arange(len(dimyt0),dtype=np.float)/(len(dimyt0)) #pixkind = 'fixpixel' else: dimxv0 = dimvv.copy() dimyv0 = dimtv.copy() dxn = dimvv.min() dxx = dimvv.max() dyn = dimtv.min() dyx = dimtv.max() if vaxv[0] == 'pretty': dimxt0 = np.array(gen.pretty_int(dxn,dxx+(dxx-dxn)/vaxv[2],vaxv[2])) elif vaxv[0] == 'Nfix': dimxt0 = np.arange(dxn,dxx,(dxx-dxn)/(1.*vaxv[2])) elif vaxv[0] == 'Vfix': dimxt0 = np.arange(0,dxx,vaxv[2]) dimxl0 = [] for i in range(len(dimxt0)): dimxl0.append('{:{style}}'.format(dimxt0[i], \ style=vaxv[1])) dimxT0 = gen.latex_text(variables_values(dimn[0])[0]) + ' (' + \ units_lunits(dimvu) + ')' dimyt0 = tpos dimyl0 = tlabs dimyT0 = 'cf time' # No following data values #dimxt0 = np.arange(len(dimxt0),dtype=np.float)/(len(dimxt0)) #pixkind = 'fixpixel' if reva is not None: varsv, dimxv, dimyv, dimxt, dimyt, dimxl, dimyl, dimxT, dimyT, xtrms, ytrms= \ gen.transform(varsv, reva, dxv=dimxv0, dyv=dimyv0, dxt=dimxt0, dyt=dimyt0, \ dxl=dimxl0, dyl=dimyl0, dxtit=dimxT0, dytit=dimyT0) else: dimxv = dimxv0 dimyv = dimyv0 dimxt = dimxt0 dimyt = dimyt0 dimxl = dimxl0 dimyl = dimyl0 dimxT = dimxT0 dimyT = dimyT0 # Which kind of grid-pixel shape do we want? x, dimxt, xtrms = pixelgrid(dimxv, dimxt, xtrms, 'x', xpixk, reva) y, dimyt, ytrms = pixelgrid(dimyv, dimyt, ytrms, 'y', ypixk, reva) # Changing limits of the colors vsend = graphic_range(vs,varsv) plt.rc('text', usetex=True) plt.pcolormesh(x, y, varsv, cmap=plt.get_cmap(cbarv[0]), vmin=vsend[0], vmax=vsend[1]) if cbarv[2] == 'horizontal': cbar = plt.colorbar(format=cbarv[1],orientation=cbarv[2]) # From: http://stackoverflow.com/questions/32050030/rotation-of-colorbar-tick-labels-in-matplotlib ticklabels= cbar.ax.get_xticklabels() Nticks = len(ticklabels) ticklabs = [] for itick in range(Nticks): ticklabs.append(ticklabels[itick].get_text()) cbar.ax.set_xticklabels(ticklabs,rotation=90) else: cbar = plt.colorbar(format=cbarv[1],orientation=cbarv[2]) if taxis == 'x': #plt.xticks((dimxt-dxn)/(dxx-dxn), dimxl) plt.xticks(dimxt, dimxl) plt.yticks(dimyt, dimyl, rotation=vaxv[3]) else: plt.xticks(dimxt, dimxl, rotation=vaxv[3]) #plt.yticks((dimyt-dyn)/(dyx-dyn), dimyl) plt.yticks(dimyt, dimyl) plt.xlabel(dimxT) plt.ylabel(dimyT) plt.axis([xtrms[0], xtrms[1], ytrms[0], ytrms[1]]) # units labels cbar.set_label(gen.latex_text(vnames) + ' (' + units_lunits(uts) + ')') figname = '2Dfields_shadow_time' graphtit = gen.latex_text(vtit) plt.title(graphtit) output_kind(kfig, figname, ifclose) return def plot_2D_shadow_contour(varsv, varcv, vnames, dimxv, dimyv, dimxu, dimyu, xaxv, \ yaxv, dimn, cbarv, ckind, clabfmt, vs, vc, uts, vtit, kfig, reva, mapv, ifclose): """ Adding labels and other staff to the graph varsv= 2D values to plot with shading varcv= 2D values to plot with contours vnames= variable names for the figure dim[x/y]v = values at the axes of x and y dim[x/y]u = units at the axes of x and y xaxv= list with the x-axis paramteres [style, format, number and orientation] yaxv= list with the y-axis paramteres [style, format, number and orientation] dimn= dimension names to plot cbarv= list with the parameters of the color bar [colorbar, cbarfmt, cbaror] colorbar= name of the color bar to use cbarfmt= format of the numbers in the colorbar cbaror= orientation of the colorbar ckind= contour kind 'cmap': as it gets from colorbar 'fixc,[colname]': fixed color [colname], all stright lines 'fixsigc,[colname]': fixed color [colname], >0 stright, <0 dashed line clabfmt= format of the labels in the contour plot (None, no labels) vs= minmum and maximum values to plot in shadow vc= vector with the levels for the contour uts= units of the variable [u-shadow, u-contour] vtit= title of the variable kfig= kind of figure (jpg, pdf, png) reva= * 'transpose': reverse the axes (x-->y, y-->x) * 'flip'@[x/y]: flip the axis x or y mapv= map characteristics: [proj],[res] see full documentation: http://matplotlib.org/basemap/ [proj]: projection * 'cyl', cilindric * 'lcc', lamvbert conformal [res]: resolution: * 'c', crude * 'l', low * 'i', intermediate * 'h', high * 'f', full ifclose= boolean value whether figure should be close (finish) or not """ fname = 'plot_2D_shadow_contour' if varsv == 'h': print fname + '_____________________________________________________________' print plot_2D_shadow_contour.__doc__ quit() if len(varsv.shape) != 2: print errormsg print ' ' + fname + ': wrong variable shadow rank:', varsv.shape, \ 'is has to be 2D!!' quit(-1) if len(varcv.shape) != 2: print errormsg print ' ' + fname + ': wrong variable contour rank:', varcv.shape, \ 'is has to be 2D!!' quit(-1) # Axis ticks # Usually axis > x must be the lon, thus... dimxv0 = dimxv.copy() dimyv0 = dimyv.copy() dxn = dimxv.min() dxx = dimxv.max() dyn = dimyv.min() dyx = dimyv.max() # sens of the original x-axis and y-axis xneg=False if len(dimxv0.shape) == 1: if dimxv0[0] > dimxv0[1]: xneg=True else: if dimxv0[0,0] > dimxv0[0,1]: xneg=True yneg=False if len(dimyv0.shape) == 1: if dimyv0[0] > dimyv0[1]: yneg=True else: if dimyv0[0,0] > dimyv0[1,0]: yneg=True if xaxv[0] == 'pretty': dimxt0 = np.array(gen.pretty_int(dxn,dxx,xaxv[2])) axxtype='data' elif xaxv[0] == 'Nfix': dimxt0 = np.arange(0.,1.,1./(xaxv[2]+1)) dimxv0 = np.arange(0.,1.,1./varsv.shape[1]) axxtype='fixpixel' elif xaxv[0] == 'Vfix': dxnvfix = int(dxn/xaxv[2]) dimxt0 = np.arange(dxnvfix*xaxv[2],dxx,xaxv[2]) axxtype='data' if yaxv[0] == 'pretty': dimyt0 = np.array(gen.pretty_int(dyn,dyx,yaxv[2])) axytype='data' elif yaxv[0] == 'Nfix': dimyt0 = np.arange(0.,1.,1./(yaxv[2]+1)) dimyv0 = np.arange(0.,1.,1./varsv.shape[0]) axytype='fixpixel' elif yaxv[0] == 'Vfix': dynvfix = int(dyn/yaxv[2]) dimyt0 = np.arange(dynvfix*xaxv[2],dyx,yaxv[2]) axytype='data' if xneg: dimxt0 = dimxt0[::-1] if yneg: dimyt0 = dimyt0[::-1] dimxl0 = [] if xaxv[0] != 'Nfix': for i in range(len(dimxt0)): dimxl0.append('{:{style}}'.format(dimxt0[i], style=xaxv[1])) else: for i in range(len(dimxt0)): xv=dxn+i*(dxx-dxn)/(1.*xaxv[2]) dimxl0.append('{:{style}}'.format(xv, style=xaxv[1])) dimyl0 = [] if yaxv[0] != 'Nfix': for i in range(len(dimyt0)): dimyl0.append('{:{style}}'.format(dimyt0[i], style=yaxv[1])) else: for i in range(len(dimyt0)): yv=dyn+i*(dyx-dyn)/(1.*yaxv[2]) dimyl0.append('{:{style}}'.format(yv, style=yaxv[1])) dimxT0 = variables_values(dimn[0])[0] + ' (' + units_lunits(dimxu) + ')' dimyT0 = variables_values(dimn[1])[0] + ' (' + units_lunits(dimyu) + ')' if reva is not None: varcv, dimxv, dimyv, dimxt, dimyt, dimxl, dimyl, dimxT, dimyT = \ transform(varcv, reva) varsv, dimxv, dimyv, dimxt, dimyt, dimxl, dimyl, dimxT, dimyT = \ transform(varsv, reva, dxv=dimxv0, dyv=dimyv0, dxt=dimxt0, dyt=dimyt0, \ dxl=dimxl0, dyl=dimyl0, dxtit=dimxT0, dytit=dimyT0, axxkind=axxtype, \ axykind=axytype) else: dimxv = dimxv0 dimyv = dimyv0 dimxt = dimxt0 dimyt = dimyt0 dimxl = dimxl0 dimyl = dimyl0 dimxT = dimxT0 dimyT = dimyT0 if not mapv is None: if len(dimxv[:].shape) == 3: lon0 = dimxv[0,] lat0 = dimyv[0,] elif len(dimxv[:].shape) == 2: lon0 = dimxv[:] lat0 = dimyv[:] elif len(dimxv[:].shape) == 1: lon00 = dimxv[:] lat00 = dimyv[:] lon0 = np.zeros( (len(lat00),len(lon00)), dtype=np.float ) lat0 = np.zeros( (len(lat00),len(lon00)), dtype=np.float ) for iy in range(len(lat00)): lon0[iy,:] = lon00 for ix in range(len(lon00)): lat0[:,ix] = lat00 map_proj=mapv.split(',')[0] map_res=mapv.split(',')[1] dx = lon0.shape[1] dy = lon0.shape[0] nlon = np.min(lon0) xlon = np.max(lon0) nlat = np.min(lat0) xlat = np.max(lat0) # Thats too much! :) # if lonlatLims is not None: # print ' ' + fname + ': cutting the domain to plot !!!!' # plt.xlim(lonlatLims[0], lonlatLims[2]) # plt.ylim(lonlatLims[1], lonlatLims[3]) # print ' limits: W-E', lonlatLims[0], lonlatLims[2] # print ' limits: N-S', lonlatLims[1], lonlatLims[3] # if map_proj == 'cyl': # nlon = lonlatLims[0] # nlat = lonlatLims[1] # xlon = lonlatLims[2] # xlat = lonlatLims[3] # elif map_proj == 'lcc': # lon2 = (lonlatLims[0] + lonlatLims[2])/2. # lat2 = (lonlatLims[1] + lonlatLims[3])/2. # nlon = lonlatLims[0] # xlon = lonlatLims[2] # nlat = lonlatLims[1] # xlat = lonlatLims[3] lon2 = lon0[dy/2,dx/2] lat2 = lat0[dy/2,dx/2] print 'lon2:', lon2, 'lat2:', lat2, 'SW pt:', nlon, ',', nlat, 'NE pt:', \ xlon, ',', xlat if map_proj == 'cyl': m = Basemap(projection=map_proj, llcrnrlon=nlon, llcrnrlat=nlat, \ urcrnrlon=xlon, urcrnrlat= xlat, resolution=map_res) elif map_proj == 'lcc': m = Basemap(projection=map_proj, lat_0=lat2, lon_0=lon2, llcrnrlon=nlon, \ llcrnrlat=nlat, urcrnrlon=xlon, urcrnrlat= xlat, resolution=map_res) if len(dimxv.shape) == 1: lons, lats = np.meshgrid(dimxv, dimyv) else: if len(dimxv.shape) == 3: lons = dimxv[0,:,:] lats = dimyv[0,:,:] else: lons = dimxv[:] lats = dimyv[:] x,y = m(lons,lats) else: x,y = gen.lonlat2D(dimxv,dimyv) plt.rc('text', usetex=True) plt.pcolormesh(x, y, varsv, cmap=plt.get_cmap(cbarv[0]), vmin=vs[0], vmax=vs[1]) if cbarv[2] == 'horizontal': cbar = plt.colorbar(format=cbarv[1],orientation=cbarv[2]) # From: http://stackoverflow.com/questions/32050030/rotation-of-colorbar-tick-labels-in-matplotlib ticklabels= cbar.ax.get_xticklabels() Nticks = len(ticklabels) ticklabs = [] for itick in range(Nticks): ticklabs.append(ticklabels[itick].get_text()) cbar.ax.set_xticklabels(ticklabs,rotation=90) else: cbar = plt.colorbar(format=cbarv[1],orientation=cbarv[2]) # contour ## contkind = ckind.split(',')[0] if contkind == 'cmap': cplot = plt.contour(x, y, varcv, levels=vc) elif contkind == 'fixc': plt.rcParams['contour.negative_linestyle'] = 'solid' coln = ckind.split(',')[1] cplot = plt.contour(x, y, varcv, levels=vc, colors=coln) elif contkind == 'fixsigc': coln = ckind.split(',')[1] cplot = plt.contour(x, y, varcv, levels=vc, colors=coln) else: print errormsg print ' ' + fname + ': contour kind "' + contkind + '" not defined !!!!!' quit(-1) if clabfmt is not None: plt.clabel(cplot, fmt=clabfmt) mincntS = format(vc[0], clabfmt[1:len(clabfmt)]) maxcntS = format(vc[len(vc)-1], clabfmt[1:len(clabfmt)]) else: mincntS = '{:g}'.format(vc[0]) maxcntS = '{:g}'.format(vc[len(vc)-1]) if not mapv is None: m.drawcoastlines() meridians = gen.pretty_int(nlon,xlon,xaxv[2]) m.drawmeridians(meridians,labels=[True,False,False,True]) parallels = gen.pretty_int(nlat,xlat,yaxv[2]) m.drawparallels(parallels,labels=[False,True,True,False]) plt.xlabel('W-E') plt.ylabel('S-N') else: plt.xlabel(dimxT) plt.ylabel(dimyT) plt.xticks(dimxt, dimxl, rotation=xaxv[3]) plt.yticks(dimyt, dimyl, rotation=yaxv[3]) #set the limits of the plot to the limits of the data plt.axis([x[0,0], x[0,x.shape[1]-1], y[0,0], y[y.shape[0]-1,0]]) # units labels cbar.set_label(gen.latex_text(vnames[0]) + ' (' + units_lunits(uts[0]) + ')') plt.annotate(gen.latex_text(vnames[1]) +' (' + units_lunits(uts[1]) + ') [' + \ mincntS + ', ' + maxcntS + ']', xy=(0.55,0.04), xycoords='figure fraction', \ color=coln) figname = '2Dfields_shadow-contour' graphtit = gen.latex_text(vtit) plt.title(graphtit) output_kind(kfig, figname, ifclose) return #Nvals=50 #vals1 = np.zeros((Nvals,Nvals), dtype= np.float) #vals2 = np.zeros((Nvals,Nvals), dtype= np.float) #for j in range(Nvals): # for i in range(Nvals): # vals1[j,i]=np.sqrt((j-Nvals/2)**2. + (i-Nvals/2)**2.) # vals2[j,i]=np.sqrt((j-Nvals/2)**2. + (i-Nvals/2)**2.) - Nvals/2 #prettylev=gen.pretty_int(-Nvals/2,Nvals/2,10) #plot_2D_shadow_contour(vals1, vals2, ['var1', 'var2'], np.arange(50)*1., \ # np.arange(50)*1., ['x-axis','y-axis'], 'rainbow', 'fixc,b', "%.2f", [0, Nvals], \ # prettylev, ['$ms^{-1}$','$kJm^{-1}s^{-1}$'], 'test var1 & var2', 'pdf', False) def plot_2D_shadow_contour_time(varsv, varcv, vnames, valv, timv, timpos, timlab, \ valu, timeu, axist, xaxv, yaxv, dimn, cbarv, ckind, clabfmt, vs, vc, uts, vtit, \ kfig, reva, ifclose): """ Adding labels and other staff to the graph varsv= 2D values to plot with shading varcv= 2D values to plot with contours vnames= variable names for the figure valv = values at the axes which is not time timv = values for the axis time timpos = positions at the axis time timlab = labes at the axis time valu = units at the axes which is not time timeu = units at the axes which is time axist = which is the axis time xaxv= list with the x-axis paramteres [style, format, number and orientation] yaxv= list with the y-axis paramteres [style, format, number and orientation] dimn= dimension names to plot cbarv= list with the parameters of the color bar [colorbar, cbarfmt, cbaror] colorbar= name of the color bar to use cbarfmt= format of the numbers in the colorbar cbaror= orientation of the colorbar ckind= contour kind 'cmap': as it gets from colorbar 'fixc,[colname]': fixed color [colname], all stright lines 'fixsigc,[colname]': fixed color [colname], >0 stright, <0 dashed line clabfmt= format of the labels in the contour plot (None, no labels) vs= minmum and maximum values to plot in shadow vc= vector with the levels for the contour uts= units of the variable [u-shadow, u-contour] vtit= title of the variable kfig= kind of figure (jpg, pdf, png) reva= * 'transpose': reverse the axes (x-->y, y-->x) * 'flip'@[x/y]: flip the axis x or y ifclose= boolean value whether figure should be close (finish) or not """ fname = 'plot_2D_shadow_contour_time' if varsv == 'h': print fname + '_____________________________________________________________' print plot_2D_shadow_contour_time.__doc__ quit() # Check variable consistency if len(varsv.shape) != 2: print errormsg print ' ' + fname + ': wrong variable shadow rank:', varsv.shape, \ 'is has to be 2D!!' quit(-1) if len(varcv.shape) != 2: print errormsg print ' ' + fname + ': wrong variable contour rank:', varcv.shape, \ 'is has to be 2D!!' quit(-1) # Axis ticks # Usually time axis is the most upper dimension, thus... dimxv0 = valv.copy() dimyv0 = timv.copy() dxn = dimxv0.min() dxx = dimxv0.max() dyn = dimyv0.min() dyx = dimyv0.max() # Time ticks-labels are already given from another function if xaxv[0] == 'pretty': dimxt0 = np.array(gen.pretty_int(dxn,dxx,xaxv[2])) elif xaxv[0] == 'Nfix': dimxt0 = np.arange(0.,1.+1./xaxv[2],1./xaxv[2]) dimxv0 = np.arange(0.,1.,1./valv.shape[0]) elif xaxv[0] == 'Vfix': dimxt0 = np.arange(0,dxx,xaxv[2]) dimyt0 = np.array(timpos) dimxl0 = [] if xaxv[0] != 'Nfix': for i in range(len(dimxt0)): dimxl0.append('{:{style}}'.format(dimxt0[i], \ style=xaxv[1])) else: for i in range(len(dimxt0)): xv=dxn+i*(dxx-dxn)/(1.*(xaxv[2])) dimxl0.append('{:{style}}'.format(xv, style=xaxv[1])) dimyl0 = list(timlab) dimxT0 = gen.latex_text(variables_values(dimn[0])[0]) +' ('+ units_lunits(valu) +\ ')' dimyT0 = timeu # Variable values usually will have time variable as 0 dimension reva = None if axist == 'x': print warnmsg print ' ' + fname + ': imposing transposition of values due to use time ' + \ 'variable at the x-axis!!' reva = 'transpose' dimxT0 = gen.latex_text(variables_values(dimn[1])[0]) + ' (' + \ units_lunits(valu) + ')' if reva is not None: varcv, dimxv, dimyv, dimxt, dimyt, dimxl, dimyl, dimxT, dimyT = \ transform(varcv, reva) varsv, dimxv, dimyv, dimxt, dimyt, dimxl, dimyl, dimxT, dimyT = \ transform(varsv, reva, dxv=dimxv0, dyv=dimyv0, dxt=dimxt0, dyt=dimyt0, \ dxl=dimxl0, dyl=dimyl0, dxtit=dimxT0, dytit=dimyT0) else: dimxv = dimxv0 dimyv = dimyv0 dimxt = dimxt0 dimyt = dimyt0 dimxl = dimxl0 dimyl = dimyl0 dimxT = dimxT0 dimyT = dimyT0 dx=varsv.shape[1] dy=varsv.shape[0] x,y = gen.lonlat2D(dimxv,dimyv) # Changing limits of the colors vsend = graphic_range(vs,varsv) plt.rc('text', usetex=True) plt.xticks(dimxt, dimxl, rotation=xaxv[3]) plt.yticks(dimyt, dimyl, rotation=yaxv[3]) # plt.xlim(dimxt[0],dimxt[len(dimxt)-1]) # plt.ylim(dimyt[0],dimyt[len(dimyt)-1]) plt.pcolormesh(x, y, varsv, cmap=plt.get_cmap(cbarv[0]), vmin=vsend[0], vmax=vsend[1]) if cbarv[2] == 'horizontal': cbar = plt.colorbar(format=cbarv[1],orientation=cbarv[2]) # From: http://stackoverflow.com/questions/32050030/rotation-of-colorbar-tick-labels-in-matplotlib ticklabels= cbar.ax.get_xticklabels() Nticks = len(ticklabels) ticklabs = [] for itick in range(Nticks): ticklabs.append(ticklabels[itick].get_text()) cbar.ax.set_xticklabels(ticklabs,rotation=90) else: cbar = plt.colorbar(format=cbarv[1],orientation=cbarv[2]) # contour ## contkind = ckind.split(',')[0] if contkind == 'cmap': cplot = plt.contour(x, y, varcv, levels=vc) elif contkind == 'fixc': plt.rcParams['contour.negative_linestyle'] = 'solid' coln = ckind.split(',')[1] cplot = plt.contour(x, y, varcv, levels=vc, colors=coln) elif contkind == 'fixsigc': coln = ckind.split(',')[1] cplot = plt.contour(x, y, varcv, levels=vc, colors=coln) else: print errormsg print ' ' + fname + ': contour kind "' + contkind + '" not defined !!!!!' quit(-1) if clabfmt is not None: plt.clabel(cplot, fmt=clabfmt) mincntS = format(vc[0], clabfmt[1:len(clabfmt)]) maxcntS = format(vc[len(vc)-1], clabfmt[1:len(clabfmt)]) else: mincntS = '{:g}'.format(vc[0]) maxcntS = '{:g}'.format(vc[len(vc)-1]) plt.xlabel(dimxT) plt.ylabel(dimyT) # set the limits of the plot to the limits of the data # plt.axis([dimxv.min(), dimxv.max(), dimyv.min(), dimyv.max()]) # units labels cbar.set_label(gen.latex_text(vnames[0]) + ' (' + units_lunits(uts[0]) + ')') plt.annotate(gen.latex_text(vnames[1]) +' (' + units_lunits(uts[1]) + ') [' + \ mincntS + ', ' + maxcntS + ']', xy=(0.55,0.04), xycoords='figure fraction', \ color=coln) figname = '2Dfields_shadow-contour' graphtit = gen.latex_text(vtit) plt.title(graphtit) output_kind(kfig, figname, ifclose) return def dxdy_lonlat(dxv,dyv,ddx,ddy): """ Function to provide lon/lat 2D lilke-matrices from any sort of dx,dy values dxdy_lonlat(dxv,dyv,Lv,lv) dx: values for the x dy: values for the y ddx: ',' list of which dimensions to use from values along x ddy: ',' list of which dimensions to use from values along y """ fname = 'dxdy_lonlat' if ddx.find(',') > -1: dxk = 2 ddxv = ddx.split(',') ddxy = int(ddxv[0]) ddxx = int(ddxv[1]) else: dxk = 1 ddxy = int(ddx) ddxx = int(ddx) if ddy.find(',') > -1: dyk = 2 ddyv = ddy.split(',') ddyy = int(ddyv[0]) ddyx = int(ddyv[1]) else: dyk = 1 ddyy = int(ddy) ddyx = int(ddy) ddxxv = dxv.shape[ddxx] ddxyv = dxv.shape[ddxy] ddyxv = dyv.shape[ddyx] ddyyv = dyv.shape[ddyy] slicex = [] if len(dxv.shape) > 1: for idim in range(len(dxv.shape)): if idim == ddxx or idim == ddxy: slicex.append(slice(0,dxv.shape[idim])) else: slicex.append(0) else: slicex.append(slice(0,len(dxv))) slicey = [] if len(dyv.shape) > 1: for idim in range(len(dyv.shape)): if idim == ddyx or idim == ddyy: slicey.append(slice(0,dyv.shape[idim])) else: slicey.append(0) else: slicey.append(slice(0,len(dyv))) if dxk == 2 and dyk == 2: if ddxxv != ddyxv: print errormsg print ' ' + fname + ': wrong dx dimensions! ddxx=',ddxxv,'ddyx=',ddyxv print ' choose another for x:',dxv.shape,'or y:',dyv.shape quit(-1) if ddxyv != ddyyv: print errormsg print ' ' + fname + ': wrong dy dimensions! ddxy=',ddxyv,'ddyy=',ddyv print ' choose another for x:',dxv.shape,'or y:',dyv.shape quit(-1) dx = ddxxv dy = ddxyv print ' ' + fname + ': final dimension 2D lon/lat-like matrices:',dy,',',dx lonv = np.zeros((dy,dx), dtype=np.float) latv = np.zeros((dy,dx), dtype=np.float) lonv = dxv[tuple(slicex)] latv = dyv[tuple(slicey)] elif dxk == 2 and dyk == 1: if not ddxxv == ddyxv and not ddxyv == ddyyv: print errormsg print ' ' + fname + ': wrong dimensions! ddxx=',ddxxv,'ddyx=',ddyxv, \ 'ddyx=',ddyxv,'ddyy=',ddyyv print ' choose another for x:',dxv.shape,'or y:',dyv.shape quit(-1) dx = ddxvv dy = ddxyv print ' ' + fname + ': final dimension 2D lon/lat-like matrices:',dy,',',dx lonv = np.zeros((dy,dx), dtype=np.float) latv = np.zeros((dy,dx), dtype=np.float) lonv = dxv[tuple(slicex)] if ddxxv == ddyxv: for iy in range(dy): latv[iy,:] = dyv[tuple(slicey)] else: for ix in range(dx): latv[:,ix] = dyv[tuple(slicey)] elif dxk == 1 and dyk == 2: if not ddxxv == ddyxv and not ddxyv == ddyyv: print errormsg print ' ' + fname + ': wrong dimensions! ddxx=',ddxxv,'ddyx=',ddyxv, \ 'ddyx=',ddyxv,'ddyy=',ddyyv print ' choose another for x:',dxv.shape,'or y:',dyv.shape quit(-1) dx = ddyxv dy = ddyyv print ' ' + fname + ': final dimension 2D lon/lat-like matrices:',dy,',',dx lonv = np.zeros((dy,dx), dtype=np.float) latv = np.zeros((dy,dx), dtype=np.float) latv = dyv[tuple(slicey)] if ddyxv == ddxxv: for iy in range(dy): lonv[iy,:] = dxv[tuple(slicex)] else: for ix in range(dx): lonv[:,ix] = dxv[tuple(slicex)] elif dxk == 1 and dyk == 1: dx = ddxxv dy = ddyyv # print 'dx:',dx,'dy:',dy lonv = np.zeros((dy,dx), dtype=np.float) latv = np.zeros((dy,dx), dtype=np.float) for iy in range(dy): lonv[iy,:] = dxv[tuple(slicex)] for ix in range(dx): latv[:,ix] = dyv[tuple(slicey)] return lonv,latv def dxdy_lonlatDIMS(dxv,dyv,dnx,dny,dd,error=True): """ Function to provide lon/lat 2D lilke-matrices from any sort of dx,dy values for a given list of values dxdy_lonlat(dxv,dyv,Lv,lv) dxv: values for the x dyv: values for the y dnx: mnames of the dimensions for values on x dny: mnames of the dimensions for values on y dd: list of [dimname]|[val] for the dimensions use [dimname]: name of the dimension [val]: value (-1 for all the range) error: whether script should quit if final shapes do not coincide """ fname = 'dxdy_lonlatDIMS' slicex = [] ipos=0 for dn in dnx: for idd in range(len(dd)): dname = dd[idd].split('|')[0] dvalue = dd[idd].split('|')[1] if dn == dname: if dvalue.find('@') != -1: slicex.append(slice(int(dvalue.split('@')[0]), \ int(dvalue.split('@')[1]))) else: if int(dvalue) == -1: slicex.append(slice(0,dxv.shape[ipos])) elif int(dvalue) == -9: slicex.append(dxv.shape[ipos]-1) else: slicex.append(int(dvalue)) break ipos = ipos + 1 slicey = [] ipos=0 for dn in dny: for idd in range(len(dd)): dname = dd[idd].split('|')[0] dvalue = dd[idd].split('|')[1] if dn == dname: if dvalue.find('@') != -1: slicey.append(slice(int(dvalue.split('@')[0]), \ int(dvalue.split('@')[1]))) else: if int(dvalue) == -1: slicey.append(slice(0,dyv.shape[ipos])) elif int(dvalue) == -9: slicey.append(dyv.shape[ipos]-1) else: slicey.append(int(dvalue)) break ipos = ipos + 1 lonv = dxv[tuple(slicex)] latv = dyv[tuple(slicey)] if len(lonv.shape) != len(latv.shape): print ' ' + fname + ': dimension size on x:', len(lonv.shape), 'and on y:', \ len(latv.shape),'do not coincide!!' if error: quit(-1) return lonv,latv def plot_2D_shadow_line(varsv, varlv, vnames, vnamel, dimxv, dimyv, dimxu, dimyu, \ dimn, xaxv, yaxv, cbarv, linev, vs, uts, utl, vtit, kfig, reva, mapv, ifclose): """ Plotting a 2D field with shadows and another one with a line varsv= 2D values to plot with shading varlv= 1D values to plot with line vnames= variable names for the shadow variable in the figure vnamel= variable names for the line varibale in the figure dim[x/y]v = values at the axes of x and y dim[x/y]u = units at the axes of x and y dimn= dimension names to plot xaxv= list with the x-axis paramteres [style, format, number and orientation] yaxv= list with the y-axis paramteres [style, format, number and orientation] cbarv= list with the parameters of the color bar [colorbar, cbarfmt, cbaror] colorbar: name of the color bar to use cbarfmt: format of the numbers in the colorbar cbaror: orientation of the colorbar linev= list with the values for the line [colorline, min, max, ticks: style, format, number and orientation] vs= minmum and maximum values to plot in shadow 'Srange': for full range 'Saroundmean@val': for mean-xtrm,mean+xtrm where xtrm = np.min(mean-min@val,max@val-mean) 'Saroundminmax@val': for min*val,max*val 'Saroundpercentile@val': for median-xtrm,median+xtrm where xtrm = np.min(median-percentile_(val), percentile_(100-val)-median) 'Smean@val': for -xtrm,xtrm where xtrm = np.min(mean-min*@val,max*@val-mean) 'Smedian@val': for -xtrm,xtrm where xtrm = np.min(median-min@val,max@val-median) 'Spercentile@val': for -xtrm,xtrm where xtrm = np.min(median-percentile_(val), percentile_(100-val)-median) uts= units of the variable to shadow utl= units of the variable to line vtit= title of the variable kfig= kind of figure (jpg, pdf, png) reva= * 'transpose': reverse the axes (x-->y, y-->x) * 'flip'@[x/y]: flip the axis x or y mapv= map characteristics: [proj],[res] see full documentation: http://matplotlib.org/basemap/ [proj]: projection * 'cyl', cilindric * 'lcc', lambert conformal [res]: resolution: * 'c', crude * 'l', low * 'i', intermediate * 'h', high * 'f', full ifclose= boolean value whether figure should be close (finish) or not """ ## import matplotlib as mpl ## mpl.use('Agg') ## import matplotlib.pyplot as plt fname = 'plot_2D_shadow_line' if varsv == 'h': print fname + '_____________________________________________________________' print plot_2D_shadow_line.__doc__ quit() if len(varsv.shape) != 2: print errormsg print ' ' + fname + ': wrong variable shadow rank:', varsv.shape, \ 'is has to be 2D!!' quit(-1) if len(varlv.shape) != 1: print errormsg print ' ' + fname + ': wrong variable line rank:', varlv.shape, \ 'is has to be 1D!!' quit(-1) # Axis ticks # Usually axis > x must be the lon, thus... dimxv0 = dimxv.copy() dimyv0 = dimyv.copy() dxn = dimxv.min() dxx = dimxv.max() dyn = dimyv.min() dyx = dimyv.max() if xaxv[0] == 'pretty': dimxt0 = np.array(gen.pretty_int(dxn,dxx,xaxv[2])) elif xaxv[0] == 'Nfix': dimxt0 = np.arange(dxn,dxx,(dxx-dxn)/(1.*xaxv[2])) elif xaxv[0] == 'Vfix': dimxt0 = np.arange(0,dxx,xaxv[2]) if yaxv[0] == 'pretty': dimyt0 = np.array(gen.pretty_int(dyn,dyx,yaxv[2])) elif yaxv[0] == 'Nfix': dimyt0 = np.arange(dyn,dyx,(dyx-dyn)/(1.*yaxv[2])) elif yaxv[0] == 'Vfix': dimyt0 = np.arange(0,dyx,yaxv[2]) dimxl0 = [] for i in range(len(dimxt0)): dimxl0.append('{:{style}}'.format(dimxt0[i], style=xaxv[1])) dimyl0 = [] for i in range(len(dimyt0)): dimyl0.append('{:{style}}'.format(dimyt0[i], style=yaxv[1])) dimxT0 = variables_values(dimn[0])[0] + ' (' + units_lunits(dimxu) + ')' dimyT0 = variables_values(dimn[1])[0] + ' (' + units_lunits(dimyu) + ')' if mapv is not None: pixkind = 'data' else: # No following data values dimxt0 = np.arange(len(dimxt0),dtype=np.float)/(len(dimxt0)) dimyt0 = np.arange(len(dimyt0),dtype=np.float)/(len(dimyt0)) pixkind = 'fixpixel' if reva is not None: varsv, dimxv, dimyv, dimxt, dimyt, dimxl, dimyl, dimxT, dimyT = \ transform(varsv, reva, dxv=dimxv0, dyv=dimyv0, dxt=dimxt0, dyt=dimyt0, \ dxl=dimxl0, dyl=dimyl0, dxtit=dimxT0, dytit=dimyT0) else: dimxv = dimxv0 dimyv = dimyv0 dimxt = dimxt0 dimyt = dimyt0 dimxl = dimxl0 dimyl = dimyl0 dimxT = dimxT0 dimyT = dimyT0 if len(dimxv[:].shape) == 3: xdims = '1,2' elif len(dimxv[:].shape) == 2: xdims = '0,1' elif len(dimxv[:].shape) == 1: xdims = '0' if len(dimyv[:].shape) == 3: ydims = '1,2' elif len(dimyv[:].shape) == 2: ydims = '0,1' elif len(dimyv[:].shape) == 1: ydims = '0' # lon0 = dimxv # lat0 = dimyv lon0, lat0 = dxdy_lonlat(dimxv,dimyv, xdims, ydims) if not mapv is None: map_proj=mapv.split(',')[0] map_res=mapv.split(',')[1] dx = lon0.shape[1] dy = lat0.shape[0] nlon = np.min(lon0) xlon = np.max(lon0) nlat = np.min(lat0) xlat = np.max(lat0) lon2 = lon0[dy/2,dx/2] lat2 = lat0[dy/2,dx/2] print 'lon2:', lon2, 'lat2:', lat2, 'SW pt:', nlon, ',', nlat, 'NE pt:', \ xlon, ',', xlat if map_proj == 'cyl': m = Basemap(projection=map_proj, llcrnrlon=nlon, llcrnrlat=nlat, \ urcrnrlon=xlon, urcrnrlat= xlat, resolution=map_res) elif map_proj == 'lcc': m = Basemap(projection=map_proj, lat_0=lat2, lon_0=lon2, llcrnrlon=nlon, \ llcrnrlat=nlat, urcrnrlon=xlon, urcrnrlat= xlat, resolution=map_res) else: print errormsg print ' ' + fname + ": map projection '" + map_proj + "' not defined!!!" print ' available: cyl, lcc' quit(-1) x,y = m(lon0,lat0) else: x = (dimxv-np.min(dimxv))/(np.max(dimxv) - np.min(dimxv)) y = (dimyv-np.min(dimyv))/(np.max(dimyv) - np.min(dimyv)) # Changing limits of the colors vsend = graphic_range(vs,varsv) plt.rc('text', usetex=True) plt.pcolormesh(x, y, varsv, cmap=plt.get_cmap(cbarv[0]), vmin=vsend[0], \ vmax=vsend[1]) if cbarv[2] == 'horizontal': cbar = plt.colorbar(format=cbarv[1],orientation=cbarv[2]) # From: http://stackoverflow.com/questions/32050030/rotation-of-colorbar-tick-labels-in-matplotlib ticklabels= cbar.ax.get_xticklabels() Nticks = len(ticklabels) ticklabs = [] for itick in range(Nticks): ticklabs.append(ticklabels[itick].get_text()) cbar.ax.set_xticklabels(ticklabs,rotation=90) else: cbar = plt.colorbar(format=cbarv[1],orientation=cbarv[2]) if not mapv is None: if cbarv[0] == 'gist_gray': m.drawcoastlines(color="red") else: m.drawcoastlines() meridians = gen.pretty_int(nlon,xlon,xaxv[2]) m.drawmeridians(meridians,labels=[True,False,False,True]) parallels = gen.pretty_int(nlat,xlat,xaxv[2]) m.drawparallels(parallels,labels=[False,True,True,False]) plt.xlabel('W-E') plt.ylabel('S-N') else: plt.xlabel(dimxT) plt.ylabel(dimyT) # Line ## # Line does not suffer the flipping of the y-axis it is independent to it # if reva is not None and reva[0:4] == 'flip' and reva.split('@')[1] == 'y': # b=-np.max(y)/np.max(varlv) # a=np.max(y) # else: # b=np.max(y)/np.max(varlv) # a=0. vlsend = graphic_range([linev[1],linev[2]],varlv) b=(1.-vlsend[0])/(vlsend[1]-vlsend[0]) a=0. newlinv = varlv*b+a if reva is not None and reva == 'transpose': plt.plot(newlinv, x, '-', color=linev[0], linewidth=2) else: plt.plot(x, newlinv, '-', color=linev[0], linewidth=2) plt.axis([x.min(), x.max(), y.min(), y.max()]) plt.tick_params(axis='y',right='off') if mapv is None: plt.xticks(dimxt, dimxl, rotation=xaxv[3]) plt.yticks(dimyt, dimyl, rotation=yaxv[3]) # units labels cbar.set_label(gen.latex_text(vnames) + ' (' + units_lunits(uts) + ')') # line ticks dln = vlsend[0] dlx = vlsend[1] if linev[3] == 'pretty': dimlt = np.array(gen.pretty_int(dln,dlx,yaxv[2])) elif linev[3] == 'Nfix': dimlt = np.arange(dln,dlx,(dlx-dln)/(1.*yaxv[2])) elif linev[3] == 'Vfix': dimlt = np.arange(0,dlx,yaxv[2]) dimll = [] for i in range(len(dimlt)): dimll.append('{:{style}}'.format(dimlt[i], style=linev[4])) for it in range(len(dimlt)): yval = (dimlt[it]*b+a) plt.plot([x.max()*0.97, x.max()], [yval, yval], '-', color='k') plt.annotate(dimll[it], xy=(1.01,yval), xycoords='axes fraction',rotation=linev[6]) # plt.annotate(tllabels[it], xy=(1.01,tllabels[it]/np.max(varlv)), \ # xycoords='axes fraction') plt.annotate(gen.latex_text(vnamel)+ ' ('+units_lunits(utl)+')', xy=(0.75,0.04), \ xycoords='figure fraction', color=linev[0]) figname = '2Dfields_shadow_line' graphtit = gen.latex_text(vtit) plt.title(graphtit) output_kind(kfig, figname, ifclose) return def plot_2D_shadow_line_time(varsv, varlv, vnames, vnamel, dimxv, dimyv, dimxu, \ dimyu, dimn, xaxv, yaxv, cbarv, linev, vs, uts, utl, vtit, kfig, reva, taxis, \ tpos, tlabs, ifclose): """ Plotting a 2D field with shadows and another one with a line evolving along time varsv= 2D values to plot with shading varlv= 1D values to plot with line vnames= variable names for the shadow variable in the figure vnamel= variable names for the line varibale in the figure dim[x/y]v = values at the axes of x and y dim[x/y]u = units at the axes of x and y dimn= dimension names to plot xaxv= list with the x-axis paramteres [style, format, number and orientation] yaxv= list with the y-axis paramteres [style, format, number and orientation] cbarv= list with the parameters of the color bar [colorbar, cbarfmt, cbaror] colorbar: name of the color bar to use cbarfmt: format of the numbers in the colorbar cbaror: orientation of the colorbar linev= list with the values for the line [colorline, min, max, ticks: style, format, number and orientation] vs= minmum and maximum values to plot in shadow 'Srange': for full range 'Saroundmean@val': for mean-xtrm,mean+xtrm where xtrm = np.min(mean-min@val,max@val-mean) 'Saroundminmax@val': for min*val,max*val 'Saroundpercentile@val': for median-xtrm,median+xtrm where xtrm = np.min(median-percentile_(val), percentile_(100-val)-median) 'Smean@val': for -xtrm,xtrm where xtrm = np.min(mean-min*@val,max*@val-mean) 'Smedian@val': for -xtrm,xtrm where xtrm = np.min(median-min@val,max@val-median) 'Spercentile@val': for -xtrm,xtrm where xtrm = np.min(median-percentile_(val), percentile_(100-val)-median) uts= units of the variable to shadow utl= units of the variable to line vtit= title of the variable kfig= kind of figure (jpg, pdf, png) reva= * 'transpose': reverse the axes (x-->y, y-->x) * 'flip'@[x/y]: flip the axis x or y taxis= axis in which provide time tpos= position of the time ticks tlabs= labels of the time ticks ifclose= boolean value whether figure should be close (finish) or not """ ## import matplotlib as mpl ## mpl.use('Agg') ## import matplotlib.pyplot as plt fname = 'plot_2D_shadow_line_time' if varsv == 'h': print fname + '_____________________________________________________________' print plot_2D_shadow_line_time.__doc__ quit() if len(varsv.shape) != 2: print errormsg print ' ' + fname + ': wrong variable shadow rank:', varsv.shape, \ 'is has to be 2D!!' quit(-1) if len(varlv.shape) != 1: print errormsg print ' ' + fname + ': wrong variable line rank:', varlv.shape, \ 'is has to be 1D!!' quit(-1) # Axis ticks dimxv0 = dimxv.copy() dimyv0 = dimyv.copy() dxn = dimxv.min() dxx = dimxv.max() dyn = dimyv.min() dyx = dimyv.max() # Definning ticks labels if taxis == 'x': dimxt0 = (tpos-np.min(tpos))/(np.max(tpos)-np.min(tpos)) dimxl0 = tlabs dimxT0 = dimxu if yaxv[0] == 'pretty': dimyt0 = np.array(gen.pretty_int(dyn,dyx,yaxv[2])) elif yaxv[0] == 'Nfix': dimyt0 = np.arange(dyn,dyx,(dyx-dyn)/(1.*yaxv[2])) elif yaxv[0] == 'Vfix': dimyt0 = np.arange(0,dyx,yaxv[2]) dimyl0 = [] for i in range(len(dimyt0)): dimyl0.append('{:{style}}'.format(dimyt0[i], \ style=xaxv[1])) dimyT0 = variables_values(dimn[1])[0] + ' (' + units_lunits(dimyu) + ')' # No following data values dimyt0 = np.arange(len(dimyt0),dtype=np.float)/(len(dimyt0)) pixkind = 'fixpixel' else: if xaxv[0] == 'pretty': dimxt0 = np.array(gen.pretty_int(dxn,dxx,xaxv[2])) elif xaxv[0] == 'Nfix': dimxt0 = np.arange(dxn,dxx,(dxx-dxn)/(1.*xaxv[2])) elif xaxv[0] == 'Vfix': dimxt0 = np.arange(0,dxx,xaxv[2]) dimxl0 = [] for i in range(len(dimxt0)): dimxl0.append('{:{style}}'.format(dimxt0[i], \ style=yaxv[1])) dimxT0 = variables_values(dimn[0])[0] + ' (' + units_lunits(dimxu) + ')' dimyt0 = (tpos-np.min(tpos))/(np.max(tpos)-np.min(tpos)) dimyl0 = tlabs dimyT0 = dimyu # No following data values dimxt0 = np.arange(len(dimxt0),dtype=np.float)/(len(dimxt0)) pixkind = 'fixpixel' if reva is not None: varsv, dimxv, dimyv, dimxt, dimyt, dimxl, dimyl, dimxT, dimyT = \ transform(varsv, reva, dxv=dimxv0, dyv=dimyv0, dxt=dimxt0, dyt=dimyt0, \ dxl=dimxl0, dyl=dimyl0, dxtit=dimxT0, dytit=dimyT0) else: dimxv = dimxv0 dimyv = dimyv0 dimxt = dimxt0 dimyt = dimyt0 dimxl = dimxl0 dimyl = dimyl0 dimxT = dimxT0 dimyT = dimyT0 if len(dimxv[:].shape) == 3: xdims = '1,2' elif len(dimxv[:].shape) == 2: xdims = '0,1' elif len(dimxv[:].shape) == 1: xdims = '0' if len(dimyv[:].shape) == 3: ydims = '1,2' elif len(dimyv[:].shape) == 2: ydims = '0,1' elif len(dimyv[:].shape) == 1: ydims = '0' # lon0 = dimxv # lat0 = dimyv lon0, lat0 = dxdy_lonlat(dimxv,dimyv, xdims, ydims) # x0 = (dimxv-np.min(dimxv))/(np.max(dimxv) - np.min(dimxv)) # y0 = (dimyv-np.min(dimyv))/(np.max(dimyv) - np.min(dimyv)) x = (lon0-np.min(lon0))/(np.max(lon0) - np.min(lon0)) y = (lat0-np.min(lat0))/(np.max(lat0) - np.min(lat0)) # Changing limits of the colors vsend = graphic_range(vs,varsv) plt.rc('text', usetex=True) plt.pcolormesh(x, y, varsv, cmap=plt.get_cmap(cbarv[0]), vmin=vsend[0], \ vmax=vsend[1]) if cbarv[2] == 'horizontal': cbar = plt.colorbar(format=cbarv[1],orientation=cbarv[2]) # From: http://stackoverflow.com/questions/32050030/rotation-of-colorbar-tick-labels-in-matplotlib ticklabels= cbar.ax.get_xticklabels() Nticks = len(ticklabels) ticklabs = [] for itick in range(Nticks): ticklabs.append(ticklabels[itick].get_text()) cbar.ax.set_xticklabels(ticklabs,rotation=90) else: cbar = plt.colorbar(format=cbarv[1],orientation=cbarv[2]) plt.xlabel(dimxT) plt.ylabel(dimyT) # Line ## # Line does not suffer the flipping of the y-axis it is independent to it # if reva is not None and reva[0:4] == 'flip' and reva.split('@')[1] == 'y': # b=-np.max(y)/np.max(varlv) # a=np.max(y) # else: # b=np.max(y)/np.max(varlv) # a=0. vlsend = graphic_range([linev[1],linev[2]],varlv) newlinv = (varlv-np.min(varlv))/(np.max(varlv)-np.min(varlv)) if reva is not None and reva == 'transpose': plt.plot(newlinv, y, '-', color=linev[0], linewidth=2) else: plt.plot(x, newlinv, '-', color=linev[0], linewidth=2) plt.axis([x.min(), x.max(), y.min(), y.max()]) plt.tick_params(axis='y',right='off') plt.xticks(dimxt, dimxl, rotation=xaxv[3]) plt.yticks(dimyt, dimyl, rotation=yaxv[3]) # units labels cbar.set_label(gen.latex_text(vnames) + ' (' + units_lunits(uts) + ')') # line ticks dln = vlsend[0] dlx = vlsend[1] if linev[3] == 'pretty': dimlt = np.array(gen.pretty_int(dln,dlx,yaxv[2])) elif linev[3] == 'Nfix': dimlt = np.arange(dln,dlx,(dlx-dln)/(1.*yaxv[2])) elif linev[3] == 'Vfix': dimlt = np.arange(0,dlx,yaxv[2]) dimll = [] for i in range(len(dimlt)): dimll.append('{:{style}}'.format(dimlt[i], style=linev[4])) for it in range(1,len(dimlt)): yval = (dimlt[it]-np.min(varlv))/(np.max(varlv)-np.min(varlv)) plt.plot([x.max()*0.97, x.max()], [yval, yval], '-', color='k') plt.annotate(dimll[it], xy=(1.01,yval), xycoords='axes fraction') plt.annotate(gen.latex_text(vnamel)+ ' ('+units_lunits(utl)+')', xy=(0.75,0.04), \ xycoords='figure fraction', color=linev[0]) figname = '2Dfields_shadow_line' graphtit = gen.latex_text(vtit) plt.title(graphtit) output_kind(kfig, figname, ifclose) return def plot_Neighbourghood_evol(varsv, dxv, dyv, vnames, ttits, tpos, tlabels, cbarv, \ neighv, Nng, vs, uts, gtit, kfig, ifclose): """ Plotting neighbourghood evolution varsv= 2D values to plot with shading vnames= shading variable name for the figure d[x/y]v= values at the axes of x and y ttits= titles of both time axis tpos= positions of the time ticks tlabels= labels of the time ticks cbarv= list with the parameters of the color bar [colorbar, cbarfmt, cbaror] colorbar: name of the color bar to use cbarfmt: format of the numbers in the colorbar cbaror: orientation of the colorbar neighv = list with the parameters for the lines of the limits of the neighborhood [color, style, width] Nng= Number of grid points of the full side of the box (odd value) vs= minmum and maximum values to plot in shadow or: 'Srange': for full range 'Saroundmean@val': for mean-xtrm,mean+xtrm where xtrm = np.min(mean-min@val,max@val-mean) 'Saroundminmax@val': for min*val,max*val 'Saroundpercentile@val': for median-xtrm,median+xtrm where xtrm = np.min(median-percentile_(val), percentile_(100-val)-median) 'Smean@val': for -xtrm,xtrm where xtrm = np.min(mean-min*@val,max*@val-mean) 'Smedian@val': for -xtrm,xtrm where xtrm = np.min(median-min@val,max@val-median) 'Spercentile@val': for -xtrm,xtrm where xtrm = np.min(median-percentile_(val), percentile_(100-val)-median) uts= units of the variable to shadow gtit= title of the graph kfig= kind of figure (jpg, pdf, png) ifclose= boolean value whether figure should be close (finish) or not """ import numpy.ma as ma fname = 'plot_Neighbourghood_evol' if varsv == 'h': print fname + '_____________________________________________________________' print plot_Neighbourghood_evol.__doc__ quit() if len(varsv.shape) != 2: print errormsg print ' ' + fname + ': wrong number of dimensions of the values: ', \ varsv.shape quit(-1) varsvmask = ma.masked_equal(varsv,fillValue) vsend = np.zeros((2), dtype=np.float) # Changing limits of the colors if type(vs[0]) != type(np.float(1.)): if vs[0] == 'Srange': vsend[0] = np.min(varsvmask) elif vs[0][0:11] == 'Saroundmean': meanv = np.mean(varsvmask) permean = np.float(vs[0].split('@')[1]) minv = np.min(varsvmask)*permean maxv = np.max(varsvmask)*permean minextrm = np.min([np.abs(meanv-minv), np.abs(maxv-meanv)]) vsend[0] = meanv-minextrm vsend[1] = meanv+minextrm elif vs[0][0:13] == 'Saroundminmax': permean = np.float(vs[0].split('@')[1]) minv = np.min(varsvmask)*permean maxv = np.max(varsvmask)*permean vsend[0] = minv vsend[1] = maxv elif vs[0][0:17] == 'Saroundpercentile': medianv = np.median(varsvmask) valper = np.float(vs[0].split('@')[1]) minv = np.percentile(varsvmask, valper) maxv = np.percentile(varsvmask, 100.-valper) minextrm = np.min([np.abs(medianv-minv), np.abs(maxv-medianv)]) vsend[0] = medianv-minextrm vsend[1] = medianv+minextrm elif vs[0][0:5] == 'Smean': meanv = np.mean(varsvmask) permean = np.float(vs[0].split('@')[1]) minv = np.min(varsvmask)*permean maxv = np.max(varsvmask)*permean minextrm = np.min([np.abs(meanv-minv), np.abs(maxv-meanv)]) vsend[0] = -minextrm vsend[1] = minextrm elif vs[0][0:7] == 'Smedian': medianv = np.median(varsvmask) permedian = np.float(vs[0].split('@')[1]) minv = np.min(varsvmask)*permedian maxv = np.max(varsvmask)*permedian minextrm = np.min([np.abs(medianv-minv), np.abs(maxv-medianv)]) vsend[0] = -minextrm vsend[1] = minextrm elif vs[0][0:11] == 'Spercentile': medianv = np.median(varsvmask) valper = np.float(vs[0].split('@')[1]) minv = np.percentile(varsvmask, valper) maxv = np.percentile(varsvmask, 100.-valper) minextrm = np.min([np.abs(medianv-minv), np.abs(maxv-medianv)]) vsend[0] = -minextrm vsend[1] = minextrm else: print errormsg print ' ' + fname + ": range '" + vs[0] + "' not ready!!!" quit(-1) print ' ' + fname + ': modified shadow min,max:',vsend else: vsend[0] = vs[0] if type(vs[0]) != type(np.float(1.)): if vs[1] == 'range': vsend[1] = np.max(varsv) else: vsend[1] = vs[1] plt.rc('text', usetex=True) # plt.pcolormesh(dxv, dyv, varsv, cmap=plt.get_cmap(colorbar), vmin=vsend[0], vmax=vsend[1]) plt.pcolormesh(varsvmask, cmap=plt.get_cmap(cbarv[0]), vmin=vsend[0], vmax=vsend[1]) if cbarv[2] == 'horizontal': cbar = plt.colorbar(format=cbarv[1],orientation=cbarv[2]) # From: http://stackoverflow.com/questions/32050030/rotation-of-colorbar-tick-labels-in-matplotlib ticklabels= cbar.ax.get_xticklabels() Nticks = len(ticklabels) ticklabs = [] for itick in range(Nticks): ticklabs.append(ticklabels[itick].get_text()) cbar.ax.set_xticklabels(ticklabs,rotation=90) else: cbar = plt.colorbar(format=cbarv[1],orientation=cbarv[2]) newtposx = (tpos[0][:] - np.min(dxv)) * (len(dxv)-1) * Nng / (np.max(dxv) - \ np.min(dxv)) newtposy = (tpos[1][:] - np.min(dyv)) * (len(dyv)-1) * Nng / (np.max(dyv) - \ np.min(dyv)) plt.xlim(np.min(newtposx), np.max(newtposx)) plt.ylim(np.min(newtposy), np.max(newtposy)+Nng) # Plotting neighborhood boundaries Nng2 = Nng/2. for iy in range(len(dyv)): plt.plot([np.min(newtposx),np.max(newtposx)], [newtposy[iy],newtposy[iy]], \ linestyle=neighv[1], color=neighv[0], linewidth=neighv[2]) for ix in range(len(dxv)): plt.plot([newtposx[ix],newtposx[ix]],[np.min(newtposy),np.max(newtposy)+Nng],\ linestyle=neighv[1], color=neighv[0], linewidth=neighv[2]) # Plotting center for iy in range(len(dyv)): for ix in range(len(dxv)): plt.plot([newtposx[ix]+Nng2,newtposx[ix]+Nng2], [newtposy[iy]+Nng2-0.125,\ newtposy[iy]+Nng2+0.125], linestyle=neighv[1], color=neighv[0], \ linewidth=neighv[2]) plt.plot([newtposx[ix]+Nng2-0.125,newtposx[ix]+Nng2+0.125], \ [newtposy[iy]+Nng2,newtposy[iy]+Nng2], linestyle=neighv[1], \ color=neighv[0], linewidth=neighv[2]) plt.xticks(newtposx+Nng/2., tlabels[0]) plt.yticks(newtposy+Nng/2., tlabels[1]) plt.xlabel(ttits[0]) plt.ylabel(ttits[1]) plt.axes().set_aspect('equal') # From: http://stackoverflow.com/questions/14406214/moving-x-axis-to-the-top-of-a-plot-in-matplotlib plt.axes().xaxis.tick_top plt.axes().xaxis.set_ticks_position('top') # units labels cbar.set_label(gen.latex_text(vnames) + ' (' + units_lunits(uts) + ')') figname = 'Neighbourghood_evol' graphtit = gen.latex_text(gtit) plt.title(graphtit, position=(0.5,1.05)) output_kind(kfig, figname, ifclose) return def plot_lines(vardv, varvv, vaxis, dtit, xaxv, yaxv, vrange, linesn, vtit, vunit, \ gtit, gloc, gsiz, cs, ls, ps, ws, ss, fv, fign, kfig, ifclose): """ Function to plot a collection of lines vardv= list of set of dimension values varvv= list of set of values vaxis= which axis will be used for the values ('x', or 'y') dtit= title for the common dimension xaxv= list with the x-axis paramteres [style, format, number and orientation] yaxv= list with the y-axis paramteres [style, format, number and orientation] vrange= range of values of the plot linesn= names for the legend ('*' for no label) vtit= title for the vaxis vunit= units of the vaxis gtit= main title gloc= location of the legend (0, autmoatic) 1: 'upper right', 2: 'upper left', 3: 'lower left', 4: 'lower right', 5: 'right', 6: 'center left', 7: 'center right', 8: 'lower center', 9: 'upper center', 10: 'center' gsiz= fontsize of the legend cs= list of color names ls= list of style of lines ps= list of style of points ws= list of withs of lines ss= list of size of points fv= frequency of values fign= name of the figure kfig= kind of figure ifclose= boolean value whether figure should be close (finish) or not plot_lines([np.arange(10)], [np.sin(np.arange(10)*np.pi/2.5)], 'y', 'time (s)', \ ['2.5'], 'sin', '-', 'sinus frequency dependency', 'sinus', 'pdf') """ fname = 'plot_lines' if vardv == 'h': print fname + '_____________________________________________________________' print plot_lines.__doc__ quit() # Axis ticks # Usually axis > x must be the dimension, thus... dxn = np.min(vardv) dxx = np.max(vardv) if vrange is None: dyn = np.min(varvv) dyx = np.max(varvv) else: dyn = vrange[0] dyx = vrange[1] if xaxv[0] == 'pretty': dimxt0 = np.array(gen.pretty_int(dxn,dxx,xaxv[2])) elif xaxv[0] == 'Nfix': dimxt0 = np.arange(dxn,dxx,(dxx-dxn)/(1.*xaxv[2])) elif xaxv[0] == 'Vfix': dimxt0 = np.arange(0,dxx,xaxv[2]) if yaxv[0] == 'pretty': dimyt0 = np.array(gen.pretty_int(dyn,dyx,yaxv[2])) elif yaxv[0] == 'Nfix': dimyt0 = np.arange(dyn,dyx,(dyx-dyn)/(1.*yaxv[2])) elif yaxv[0] == 'Vfix': dimyt0 = np.arange(0,dyx,yaxv[2]) dimxv0 = dimxt0 dimyv0 = dimyt0 dimxl0 = [] for i in range(len(dimxt0)): dimxl0.append('{:{style}}'.format(dimxt0[i], style=xaxv[1])) dimyl0 = [] for i in range(len(dimyt0)): dimyl0.append('{:{style}}'.format(dimyt0[i], style=yaxv[1])) dimxT0 = gen.latex_text(dtit) dimyT0 = gen.latex_text(vtit) + ' (' + units_lunits(vaxis) + ')' pixkind = 'fixpixel' if vaxis == 'y': reva = None else: reva = 'transpose' if reva is not None: varsv = np.zeros((len(dimxt0), len(dimyt0)), dtype=np.float) varsv, dimxv, dimyv, dimxt, dimyt, dimxl, dimyl, dimxT, dimyT = \ transform(varsv, reva, dxv=dimxv0, dyv=dimyv0, dxt=dimxt0, dyt=dimyt0, \ dxl=dimxl0, dyl=dimyl0, dxtit=dimxT0, dytit=dimyT0) else: dimxv = dimxv0 dimyv = dimyv0 dimxt = dimxt0 dimyt = dimyt0 dimxl = dimxl0 dimyl = dimyl0 dimxT = dimxT0 dimyT = dimyT0 Ntraj = len(vardv) # Lines' characteristics cols, lins, pts, lws, pss = ColorsLinesPointsStyles(Ntraj, cs, ls, ps, ws, ss, fv) plt.rc('text', usetex=True) if vaxis == 'x': for il in range(Ntraj): if linesn[il] == '*': plt.plot(varvv[il], vardv[il], lins[il], marker=pts[il], \ linewidth=lws[il], markersize=pss[il], color=cols[il]) else: plt.plot(varvv[il], vardv[il], lins[il], marker=pts[il], \ linewidth=lws[il], markersize=pss[il], label=linesn[il], \ color=cols[il]) plt.xlim(dyn,dyx) plt.ylim(dxn,dxx) else: for il in range(Ntraj): if linesn[il] == '*': plt.plot(vardv[il], varvv[il], lins[il], marker=pts[il], \ linewidth=lws[il], markersize=pss[il], color=cols[il]) else: plt.plot(vardv[il], varvv[il], lins[il], marker=pts[il], \ linewidth=lws[il], markersize=pss[il], label=linesn[il], \ color=cols[il]) plt.xlim(dxn,dxx) plt.ylim(dyn,dyx) plt.xlabel(dimxT) plt.ylabel(dimyT) plt.xticks(dimxt, dimxl, rotation=xaxv[3]) plt.yticks(dimyt, dimyl, rotation=yaxv[3]) graphtit = gen.latex_text(gtit) plt.title(graphtit) plt.legend(loc=gloc, prop={'size':gsiz}) output_kind(kfig, fign, ifclose) return def ColorsLinesPointsStyles(Nstyles, colors, lines, points, lwidths, psizes, ptfreq): """ Function to provide the colors, lines & points styles Nstyles= total number of styles colors= list of colors, None for no value lines= list of lines, None for no value points= list of points, None for no value lwidths= list of line widths, None for no value psizes= list of point sizes, None for no value ptfreq= frequency for the points, None for all values >>> Nstyles = 3 >>> colors = ['blue'] >>> lines = ['-'] >>> points = ['x', '*', 'o'] >>> lwidths = ['1'] >>> psizes = ['2'] >>> ptfreq = 2 >>> colors, lines, points = ColorsLinesPointsStyles(Nstyles, colors, lines, points, lwidths, psizes, ptfreq) ['blue', 'blue', 'blue'] ['-', '-', '-'] ['x', '*', 'o'] ['2', '2', '2'] ['1', '1', '1'] """ fname = 'ColorsLinesPointsStyles' usecolors = [] uselines = [] usepoints = [] usewlines = [] usespoints = [] # Colors if colors is None: Ncols = len(colorsauto) for ic in range(Nstyles): imc = int(ic/Ncols) iic = ic - imc * Ncols usecolors.append(colorsauto[iic]) else: Ncols = len(colors) if Ncols == 1: for ic in range(Nstyles): usecolors.append(colors[0]) else: if Ncols != Nstyles: print errormsg print ' ' + fname + ': number of provided colors:', Ncols, \ 'and required:', Nstyles,'differ !!' print ' provided:', colors quit(-1) usecolors = colors # Lines if lines is None: Nklns = len(linekindsauto) for il in range(Nstyles): iml = int(il/Nklns) iil = il - iml * Nklns uselines.append(linekindsauto[iil]) else: Nklns = len(lines) if Nklns == 1: for il in range(Nstyles): uselines.append(lines[0]) else: if Nklns != Nstyles: print errormsg print ' ' + fname + ': number of provided lines:', Nklns, \ 'and required:', Nstyles,'differ !!' print ' provided:', lines quit(-1) uselines = lines # Points if points is None: Nkpts = len(pointkindsauto) for ip in range(Nstyles): imc = int(ip/Nkpts) iip = ip - imc * Nkpts usepoints.append(pointkindsauto[iip]) else: Nkpts = len(points) if Nkpts == 1: for ip in range(Nstyles): usepoints.append(points[0]) else: if Nkpts != Nstyles: print errormsg print ' ' + fname + ': number of provided points:', Nkpts, \ 'and required:', Nstyles,'differ !!' print ' provided:', points quit(-1) usepoints = points # Line widths if lwidths is None: Nwlns = len(linewidthsauto) for il in range(Nstyles): iml = int(il/Nwlns) iil = il - iml * Nwlns usewlines.append(linewidthsauto[iil]) else: Nwlns = len(lwidths) if Nwlns == 1: for il in range(Nstyles): usewlines.append(lwidths[0]) else: if Nwlns != Nstyles: print errormsg print ' ' + fname + ': number of provided line widthss:', Nwlns, \ 'and required:', Nstyles, 'differ !!' print ' provided:', lwidths quit(-1) usewlines = lwidths # Point sizes if psizes is None: Nspts = len(pointsizesauto) for ip in range(Nstyles): ipc = int(ip/Nspts) iip = ip - ipc * Nspts usespoints.append(pointsizesauto[iip]) else: Nspts = len(psizes) if Nspts == 1: for ip in range(Nstyles): usespoints.append(psizes[0]) else: if Nspts != Nstyles: print errormsg print ' ' + fname + ': number of provided point sizes:', Nspts, \ 'and required:', Nstyles, 'differ !!' print ' provided:', psizes quit(-1) usespoints = psizes Ncols = len(usecolors) Nlins = len(uselines) Npnts = len(usepoints) lkinds = [] pkinds = [] lcolors = usecolors # Old way # if ptfreq is not None: # lkinds = uselines # pkinds = usepoints # else: # pkinds = usepoints # lkinds = uselines # for ilp in range(Nstyles): # lkinds.append(usepoints[ilp] + uselines[ilp]) return lcolors, uselines, usepoints, usewlines, usespoints #Nstyles = 3 ##colors = ['blue'] #colors = None #lines = ['-'] #points = ['x', '*', 'o'] #lwidths = ['2'] #psizes = ['1'] #ptfreq = 2 #print ColorsLinesPointsStyles(Nstyles, colors, lines, points, lwidths, psizes, ptfreq) def LinesPointsStyles(Nstyles, lines, points, ptfreq): """ Function to provide the lines & points styles Nstyles= total number of styles lines= list of lines, None for no value points= list of points, None for no value ptfreq= frequency for the points, None for all values >>> Nstyles = 3 >>> lines = ['-'] >>> points = ['x', '*', 'o'] >>> ptfreq = 2 >>> lines, points = LinesPointsStyles(Nstyles, lines, points, ptfreq) ['-', '-', '-'] ['x', '*', 'o'] """ fname = 'LinesPointsStyles' # Canging line kinds every 7 lines (end of standard colors) uselines = [] usepoints = [] if lines is None: Nklns = len(linekindsauto) for il in range(Nstyles): iil = np.mod(il,Nklns) uselines.append(linekindsauto[iil]) else: Nklns = len(lines) if Nklns == 1: for il in range(Nstyles): uselines.append(lines[0]) else: if Nklns != Nstyles: print errormsg print ' ' + fname + ': number of provided lines:', Nklns, \ 'and required:', Nstyles,'differ !!' quit(-1) uselines = lines if points is None: Nkpts = len(pointkindsauto) for ip in range(Nstyles): iip = np.mod(ip,Nkpts) usepoints.append(pointkindsauto[iip]) else: Nkpts = len(points) if Nkpts == 1: for ip in range(Nstyles): usepoints.append(points[0]) else: if Nkpts != Nstyles: print errormsg print ' ' + fname + ': number of provided points:', Nkpts, \ 'and required:', Nstyles,'differ !!' quit(-1) usepoints = points Nlins = len(uselines) Npnts = len(usepoints) lkinds = [] pkinds = [] if ptfreq is not None: lkinds = uselines pkinds = usepoints else: pkinds = usepoints for ilp in range(Nstyles): lkinds.append(usepoints[ilp] + uselines[ilp]) return lkinds, pkinds def plot_lines_time(vardv, varvv, vaxis, xaxv, yaxv, dtit, linesn0, vtit, vunit, \ tpos, tlabs, gtit, gloc, gsize, kfig, vmin, vmax, lsl, coll, ptl, lwidth, psize, \ ptf, ifclose): """ Function to plot a collection of lines with a time axis vardv= list of set of dimension values varvv= list of set of values vaxis= which axis will be used for the time values ('x', or 'y') xaxv= list with the x-axis paramteres [style, format, number and orientation] yaxv= list with the y-axis paramteres [style, format, number and orientation] dtit= title for the common dimension linesn= names for the legend (None, no legend, '!' for spaces, '*' for no label) vtit= title for the vaxis vunit= units of the vaxis tpos= positions of the time ticks tlabs= labels of the time ticks gtit= main title vmin= minimum value for the axis-value 'auto' for use the extreme vmax= maximum value for the axis-value 'auto' for use the extreme gloc= location of the legend (0, autmoatic) 1: 'upper right', 2: 'upper left', 3: 'lower left', 4: 'lower right', 5: 'right', 6: 'center left', 7: 'center right', 8: 'lower center', 9: 'upper center', 10: 'center' gsize= fontsize of the legend kfig= kind of figure lsl= ',' list of line styles coll= ',' list of colors for the lines, None for automatic, single value all the same ptl= ',' list of type of points for the lines, None for automatic, single value all the same lwidth= ',' list of line widths psize= ',' list of point sizes ptf= frequency of point plotting, 'all' for all time steps ifclose= boolean value whether figure should be close (finish) or not plot_lines([np.arange(10)], [np.sin(np.arange(10)*np.pi/2.5)], 'y', 'time (s)', \ ['2.5'], 'sin', '-', 'sinus frequency dependency', 'pdf') """ fname = 'plot_lines_time' if vardv == 'h': print fname + '_____________________________________________________________' print plot_lines_time.__doc__ quit() Ntraj = len(vardv) colvalues, linekinds, pointkinds, lwidths, psizes = ColorsLinesPointsStyles( \ Ntraj, coll, lsl, ptl, lwidth, psize, ptf) # Axis ticks # Usually axis > x must be the time one, thus... # Dealing with different length of income data dxn = 1.e20 dxx = -1.e20 dyn = 1.e20 dyx = -1.e20 il = 0 for il in range(len(vardv)): dxn = np.min([np.min(vardv[il]),dxn]) dxx = np.max([np.max(vardv[il]),dxx]) dyn = np.min([np.min(varvv[il]),dyn]) dyx = np.max([np.max(varvv[il]),dyx]) print ' ' + linesn0[il], 'shape:', varvv[il].shape il = il + 1 dimxt0 = tpos if yaxv[0] == 'pretty': dimyt0 = np.array(gen.pretty_int(dyn,dyx,yaxv[2])) elif yaxv[0] == 'Nfix': dimyt0 = np.arange(dyn,dyx,(dyx-dyn)/(1.*yaxv[2])) elif yaxv[0] == 'Vfix': dimyt0 = np.arange(0,dyx,yaxv[2]) dimxv0 = dimxt0 dimyv0 = dimyt0 dimxl0 = tlabs dimyl0 = [] for i in range(len(dimyt0)): dimyl0.append('{:{style}}'.format(dimyt0[i], style=yaxv[1])) dimxT0 = gen.latex_text(dtit) dimyT0 = gen.latex_text(vtit) + ' (' + units_lunits(vaxis) + ')' pixkind = 'fixpixel' if vaxis == 'y': reva = None else: reva = 'transpose' if reva is not None: varsv = np.zeros((len(dimxt0), len(dimyt0)), dtype=np.float) varsv, dimxv, dimyv, dimxt, dimyt, dimxl, dimyl, dimxT, dimyT = \ transform(varsv, reva, dxv=dimxv0, dyv=dimyv0, dxt=dimxt0, dyt=dimyt0, \ dxl=dimxl0, dyl=dimyl0, dxtit=dimxT0, dytit=dimyT0) else: dimxv = dimxv0 dimyv = dimyv0 dimxt = dimxt0 dimyt = dimyt0 dimxl = dimxl0 dimyl = dimyl0 dimxT = dimxT0 dimyT = dimyT0 plt.rc('text', usetex=True) xtrmvv = [fillValueF,-fillValueF] xtrmdv = [fillValueF,-fillValueF] # Do we have legend? ## if linesn0 is None: linesn = [] for itrj in range(Ntraj): linesn.append(str(itrj)) else: linesn = linesn0 if vaxis == 'x': for il in range(Ntraj): if linesn[il] != '*': plt.plot(varvv[il], vardv[il], linekinds[il], marker=pointkinds[il], \ label=gen.latex_text(linesn[il].replace('!',' ')), \ color=colvalues[il], linewidth=lwidths[il], markersize=psizes[il], \ markevery=ptf) else: plt.plot(varvv[il], vardv[il], linekinds[il], marker=pointkinds[il], \ color=colvalues[il], linewidth=lwidths[il], markersize=psizes[il], \ markevery=ptf) minvv = np.min(varvv[il]) maxvv = np.max(varvv[il]) mindv = np.min(vardv[il]) maxdv = np.max(vardv[il]) if minvv < xtrmvv[0]: xtrmvv[0] = minvv if maxvv > xtrmvv[1]: xtrmvv[1] = maxvv if mindv < xtrmdv[0]: xtrmdv[0] = mindv if maxdv > xtrmdv[1]: xtrmdv[1] = maxdv plt.xlabel(gen.latext_text(vtit) + ' (' + gen.latex_text(vunit) + ')') plt.ylabel(dtit) # plt.xlim(np.min(varTvv),np.max(varTvv)) # plt.ylim(np.min(varTdv),np.max(varTdv)) if vmin == 'auto': xmin = xtrmvv[0] else: xmin = vmin if vmax == 'auto': xmax = xtrmvv[1] else: xmax = vmax plt.xlim(xmin,xmax) plt.ylim(xtrmdv[0],xtrmdv[1]) plt.yticks(tpos, tlabs) else: for il in range(Ntraj): Nvals = len(vardv[il]) if linesn[il] != '*': plt.plot(vardv[il], varvv[il], linekinds[il], marker=pointkinds[il], \ label=gen.latex_text(linesn[il]), color=colvalues[il], \ linewidth=lwidths[il], markersize=psizes[il], markevery=ptf) else: plt.plot(vardv[il], varvv[il], linekinds[il], marker=pointkinds[il], \ color=colvalues[il], linewidth=lwidths[il], markersize=psizes[il], \ markevery=ptf) minvv = np.min(varvv[il]) maxvv = np.max(varvv[il]) mindv = np.min(vardv[il]) maxdv = np.max(vardv[il]) if minvv < xtrmvv[0]: xtrmvv[0] = minvv if maxvv > xtrmvv[1]: xtrmvv[1] = maxvv if mindv < xtrmdv[0]: xtrmdv[0] = mindv if maxdv > xtrmdv[1]: xtrmdv[1] = maxdv plt.xlabel(dtit) plt.ylabel(gen.latex_text(vtit) + ' (' + vunit + ')') if vmin == 'auto': ymin = xtrmvv[0] else: ymin = vmin if vmax == 'auto': ymax = xtrmvv[1] else: ymax = vmax plt.xlim(xtrmdv[0],xtrmdv[1]) plt.ylim(ymin,ymax) # plt.xlim(np.min(varTdv),np.max(varTdv)) # plt.ylim(np.min(varTvv),np.max(varTvv)) plt.xticks(tpos, tlabs) figname = 'lines_time' graphtit = gen.latex_text(gtit) plt.title(graphtit) if linesn0 is not None: plt.legend(loc=gloc, prop={'size':gsize}) output_kind(kfig, figname, ifclose) return def plot_barbs(xvals, yvals, uvals, vvals, vecfreq, veccolor, barblength, windn, \ wuts, xaxv, yaxv, dimn, dimu, mapv, reva, graphtit, kfig, figname, ifclose): """ Function to plot wind barbs xvals= x position of the values yvals= y position of the values uvals= values for the x-wind uvals= values for the y-wind vecfreq= [xfreq],[yfreq] frequency of values allong each axis (None, all grid points; 'auto', computed automatically to have 20 vectors along each axis) veccolor= color of the vectors ('auto', for 'red') two options: [colorname]: name of the color fixed for all vectors 'colormap',[colormapname]: use colormap to provide the colors tacking wind speed as reference barblength= length of the wind barbs ('auto', for 9) windn= name of the wind variable in the graph wuts= units of the wind variable in the graph xaxv= list with the x-axis paramteres [style, format, number and orientation] yaxv= list with the y-axis paramteres [style, format, number and orientation] dimn= name of the X,Y variable-dimensions dimu= units of the X,Y variable-dimensions mapv= map characteristics: [proj],[res] see full documentation: http://matplotlib.org/basemap/ [proj]: projection * 'cyl', cilindric * 'lcc', lambert conformal [res]: resolution: * 'c', crude * 'l', low * 'i', intermediate * 'h', high * 'f', full graphtit= title of the graph ('|', for spaces) kfig= kind of figure figname= name of the figure ifclose= boolean value whether figure should be close (finish) or not """ fname = 'plot_barbs' if len(xvals.shape) != 2: print errormsg print ' ' + fname + ': wrong variable xvals rank:', xvals.shape, \ 'is has to be 2D!!' quit(-1) if len(yvals.shape) != 2: print errormsg print ' ' + fname + ': wrong variable yvals rank:', yvals.shape, \ 'is has to be 2D!!' quit(-1) if len(uvals.shape) != 2: print errormsg print ' ' + fname + ': wrong variable uvals rank:', uvals.shape, \ 'is has to be 2D!!' quit(-1) if len(vvals.shape) != 2: print errormsg print ' ' + fname + ': wrong variable vvals rank:', vvals.shape, \ 'is has to be 2D!!' quit(-1) dx=xvals.shape[1] dy=xvals.shape[0] # Axis ticks # Usually axis > x must be the lon, thus... if mapv is None: dimxv0 = xvals[0,:] dimyv0 = yvals[:,0] else: dimxv0 = xvals.copy() dimyv0 = yvals.copy() dxn = dimxv0.min() dxx = dimxv0.max() dyn = dimyv0.min() dyx = dimyv0.max() if xaxv[0] == 'pretty': dimxt0 = np.array(gen.pretty_int(dxn,dxx,xaxv[2])) elif xaxv[0] == 'Nfix': dimxt0 = np.arange(dxn,dxx,(dxx-dxn)/(1.*xaxv[2])) elif xaxv[0] == 'Vfix': dimxt0 = np.arange(0,dxx,xaxv[2]) if yaxv[0] == 'pretty': dimyt0 = np.array(gen.pretty_int(dyn,dyx,yaxv[2])) elif yaxv[0] == 'Nfix': dimyt0 = np.arange(dyn,dyx,(dyx-dyn)/(1.*yaxv[2])) elif yaxv[0] == 'Vfix': dimyt0 = np.arange(0,dyx,yaxv[2]) dimxl0 = [] for i in range(len(dimxt0)): dimxl0.append('{:{style}}'.format(dimxt0[i], \ style=xaxv[1])) dimyl0 = [] for i in range(len(dimyt0)): dimyl0.append('{:{style}}'.format(dimyt0[i], \ style=yaxv[1])) dimxT0 = variables_values(dimn[0])[0] + ' (' + units_lunits(dimu[0]) + ')' dimyT0 = variables_values(dimn[1])[0] + ' (' + units_lunits(dimu[1]) + ')' if mapv is not None: pixkind = 'data' else: # No following data values # dimxt0 = np.arange(len(dimxt0),dtype=np.float)/(len(dimxt0)) # dimyt0 = np.arange(len(dimyt0),dtype=np.float)/(len(dimyt0)) pixkind = 'fixpixel' if reva is not None: uvals, dimxv, dimyv, dimxt, dimyt, dimxl, dimyl, dimxT, dimyT = \ transform(uvals, reva) vvals, dimxv, dimyv, dimxt, dimyt, dimxl, dimyl, dimxT, dimyT = \ transform(vvals, reva, dxv=dimxv0, dyv=dimyv0, dxt=dimxt0, dyt=dimyt0, \ dxl=dimxl0, dyl=dimyl0, dxtit=dimxT0, dytit=dimyT0) else: dimxv = dimxv0 dimyv = dimyv0 dimxt = dimxt0 dimyt = dimyt0 dimxl = dimxl0 dimyl = dimyl0 dimxT = dimxT0 dimyT = dimyT0 # Frequency of vectors if vecfreq is None: xfreq = 1 yfreq = 1 elif vecfreq == 'auto': xfreq = dx/20 yfreq = dy/20 else: xfreq=int(vecfreq.split('@')[0]) yfreq=int(vecfreq.split('@')[1]) if veccolor == 'auto': bctype = 'fix' vcolor = "red" else: if veccolor.find('@') != -1: vcvals = veccolor.split('@') if vcvals[0] == 'colormap': wscol = [] bctype = 'cmap' cmap = vcvals[1] wspeed = np.sqrt(uvals[::yfreq,::xfreq]*uvals[::yfreq,::xfreq] + \ vvals[::yfreq,::xfreq]*vvals[::yfreq,::xfreq]) else: print errormsg print ' '+fname+ ": barb color type '" + vcvals[0] + "' not redy !!" else: bctype = 'fix' vcolor = veccolor if barblength == 'auto': blength = 9 else: blength = np.float(barblength) plt.rc('text', usetex=True) if not mapv is None: lon00 = np.where(xvals[:] < 0., 360. + xvals[:], xvals[:]) lat00 = yvals[:] map_proj=mapv.split(',')[0] map_res=mapv.split(',')[1] nlon = np.min(xvals[::yfreq,::xfreq]) xlon = np.max(xvals[::yfreq,::xfreq]) nlat = np.min(yvals[::yfreq,::xfreq]) xlat = np.max(yvals[::yfreq,::xfreq]) lon2 = xvals[dy/2,dx/2] lat2 = yvals[dy/2,dx/2] print 'lon2:', lon2, 'lat2:', lat2, 'SW pt:', nlon, ',', nlat, 'NE pt:', \ xlon, ',', xlat if map_proj == 'cyl': m = Basemap(projection=map_proj, llcrnrlon=nlon, llcrnrlat=nlat, \ urcrnrlon=xlon, urcrnrlat= xlat, resolution=map_res) elif map_proj == 'lcc': m = Basemap(projection=map_proj, lat_0=lat2, lon_0=lon2, llcrnrlon=nlon, \ llcrnrlat=nlat, urcrnrlon=xlon, urcrnrlat= xlat, resolution=map_res) else: print errormsg print ' ' + fname + ": projection '" + map_proj + "' not ready!!" print ' projections available: cyl, lcc' quit(-1) m.drawcoastlines() meridians = gen.pretty_int(nlon,xlon,5) m.drawmeridians(meridians,labels=[True,False,False,True],color="black") parallels = gen.pretty_int(nlat,xlat,5) m.drawparallels(parallels,labels=[False,True,True,False],color="black") plt.xlabel('W-E') plt.ylabel('S-N') else: plt.xlabel(dimxT) plt.ylabel(dimyT) # plt.axis([x.min(), x.max(), y.min(), y.max()]) if mapv is None: plt.xticks(dimxt, dimxl, rotation=xaxv[3]) plt.yticks(dimyt, dimyl, rotation=yaxv[3]) if bctype == 'fix': plt.barbs(xvals[::yfreq,::xfreq], yvals[::yfreq,::xfreq], \ uvals[::yfreq,::xfreq], vvals[::yfreq,::xfreq], color=vcolor, pivot='tip', \ length=blength) plt.annotate(windn.replace('_','\_') +' (' + units_lunits(wuts) + ')', \ xy=(0.85,-0.10), xycoords='axes fraction', color=vcolor) elif bctype == 'cmap': plt.barbs(xvals[::yfreq,::xfreq], yvals[::yfreq,::xfreq], \ uvals[::yfreq,::xfreq], vvals[::yfreq,::xfreq], wspeed, pivot='tip', \ length=blength, cmap=plt.get_cmap(cmap)) plt.annotate(windn.replace('_','\_') +' (' + units_lunits(wuts) + ')', \ xy=(0.85,-0.10), xycoords='axes fraction', color='k') # cbar = plt.colorbar() plt.title(gen.latex_text(graphtit.replace('|',' '))) ## NOT WORKING ## # No legend so it is imposed ## windlabel=windn.replace('_','\_') +' (' + units_lunits(wuts[1]) + ')' ## vecpatch = mpatches.Patch(color=vcolor, label=windlabel) ## plt.legend(handles=[vecpatch]) ## vecline = mlines.Line2D([], [], color=vcolor, marker='.', markersize=10, label=windlabel) ## plt.legend(handles=[vecline], loc=1) output_kind(kfig, figname, ifclose) return def plot_ptZvals(vname, vunits, xvn, yvn, xvu, yvu, points, xaxv, yaxv, ptype, \ ptsize, graphlims, minmax, figtitle, cbarv, legv, mapv, kfig, ifclose): """ Function to plot a given list of points and values vname= name of the variable in the graph vunits= units of the variable xvn= variable name for x-axis yvn= variable name for y-axis xvu= units for x-axis yvu= units for y-axis points= [lon,lat,val] matrix of values xaxv= list with the x-axis paramteres [style, format, number and orientation] yaxv= list with the y-axis paramteres [style, format, number and orientation] ptype= type of the point ptsize= size of the point graphlims= minLON,minLAT,maxLON,maxLAT limits of the graph, None for the full size minmax= minimum and maximum type 'auto': values taken from the extrems of the data [min],[max]: given minimum and maximum values figtitle= title of the figure cbarv= list with the parameters of the color bar [colorbar, cbarfmt, cbaror] colorbar: name of the color bar to use cbarfmt: format of the numbers in the colorbar cbaror: orientation of the colorbar legv= kind of legend 'None': no legend 'ptlabel',[varlabels],[xoffset],[yoffset]: label at the side of the point [varlabels]: variable in file with the labels for the points [xoffset]: x-offset of the label respect the point in pixels [yoffset]: y-offset of the label respect the point in pixels 'legend',[location],[fontsize]: standard legend [location]: location of the legend ('0', for automatic) 1: 'upper right', 2: 'upper left', 3: 'lower left', 4: 'lower right', 5: 'right', 6: 'center left', 7: 'center right', 8: 'lower center', 9: 'upper center', 10: 'center' [fontsize]: size of the font for the legend ('auto' for 12) mapv= map characteristics: [proj],[res] see full documentation: http://matplotlib.org/basemap/ [proj]: projection * 'cyl', cilindric * 'lcc', lambert-conformal [res]: resolution: * 'c', crude * 'l', low * 'i', intermediate * 'h', high * 'f', full kfig= kind of figure ifclose= whether figure should be closed or not """ fname = 'plot_ptZvals' figname = 'pointsZval' if graphlims is None: dxn = points[:,0].min() dxx = points[:,0].max() dyn = points[:,1].min() dyx = points[:,1].max() else: dxn = graphlims[0] dxx = graphlims[2] dyn = graphlims[1] dyx = graphlims[3] if xaxv[0] == 'pretty': dimxt0 = np.array(gen.pretty_int(dxn,dxx,xaxv[2])) elif xaxv[0] == 'Nfix': dimxt0 = np.arange(dxn,dxx,(dxx-dxn)/(1.*xaxv[2])) elif xaxv[0] == 'Vfix': dimxt0 = np.arange(0,dxx,xaxv[2]) if yaxv[0] == 'pretty': dimyt0 = np.array(gen.pretty_int(dyn,dyx,yaxv[2])) elif yaxv[0] == 'Nfix': dimyt0 = np.arange(dyn,dyx,(dyx-dyn)/(1.*yaxv[2])) elif yaxv[0] == 'Vfix': dimyt0 = np.arange(0,dyx,yaxv[2]) dimxl0 = [] for i in range(len(dimxt0)): dimxl0.append('{:{style}}'.format(dimxt0[i], style=xaxv[1])) dimyl0 = [] for i in range(len(dimyt0)): dimyl0.append('{:{style}}'.format(dimyt0[i], style=yaxv[1])) dimxT0 = variables_values(xvn)[0] + ' (' + units_lunits(xvu) + ')' dimyT0 = variables_values(yvn)[0] + ' (' + units_lunits(yvu) + ')' if mapv is not None: pixkind = 'data' else: # No following data values dimxt0 = np.arange(len(dimxt0),dtype=np.float)/(len(dimxt0)) dimyt0 = np.arange(len(dimyt0),dtype=np.float)/(len(dimyt0)) pixkind = 'fixpixel' minlon = points[:,0].min() maxlon = points[:,0].max() minlat = points[:,1].min() maxlat = points[:,1].max() minval = points[:,2].min() maxval = points[:,2].max() # print 'min/max val;',minval,maxval # Normalizing x,y for the points #lonrange = (points[:,0] - minlon)/(maxlon - minlon) #latrange = (points[:,1] - minlat)/(maxlat - minlat) #colorrange = (points[:,2] - minval)/(maxval - minval) plt.rc('text', usetex=True) if mapv is not None: vlon = points[:,0] vlat = points[:,1] dx = len(vlon) dy = len(vlat) # vlon = np.where(vlon[:] < 0., 360. + vlon[:], vlon[:]) # xvala = np.array(xval) # xvala = np.where(xvala < 0., 360. + xvala, xvala) # xval = list(xvala) map_proj=mapv.split(',')[0] map_res=mapv.split(',')[1] if graphlims is not None: nlon = graphlims[0] xlon = graphlims[2] nlat = graphlims[1] xlat = graphlims[3] else: nlon = vlon.min() xlon = vlon.max() nlat = vlat.min() xlat = vlat.max() lon2 = vlon[dy/2] lat2 = vlat[dy/2] print 'lon2:', lon2, 'lat2:', lat2, 'SW pt:', nlon, ',', nlat, 'NE pt:', \ xlon, ',', xlat if map_proj == 'cyl': m = Basemap(projection=map_proj, llcrnrlon=nlon, llcrnrlat=nlat, \ urcrnrlon=xlon, urcrnrlat= xlat, resolution=map_res) elif map_proj == 'lcc': m = Basemap(projection=map_proj, lat_0=lat2, lon_0=lon2, llcrnrlon=nlon, \ llcrnrlat=nlat, urcrnrlon=xlon, urcrnrlat= xlat, resolution=map_res) else: print errormsg print ' ' + fname + ": map projecion '" + map_proj + "' not ready!!" print ' available: cyl, lcc' quit(-1) # lons, lats = np.meshgrid(vlon, vlat) # lons = np.where(lons < 0., lons + 360., lons) x,y = m(vlon,vlat) m.drawcoastlines() meridians = gen.pretty_int(nlon,xlon,xaxv[2]) m.drawmeridians(meridians,labels=[True,False,False,True]) parallels = gen.pretty_int(nlat,xlat,yaxv[2]) m.drawparallels(parallels,labels=[False,True,True,False]) # else: # x = vlon # y = vlat # plt.xlim(0,dx-1) # plt.ylim(0,dy-1) if minmax == 'auto': plt.scatter(points[:,0], points[:,1], c=points[:,2], s=ptsize, cmap=cbarv[0],\ marker=ptype) zminv = minval zmaxv = minval else: zminv = np.float(minmax.split(',')[0]) zmaxv = np.float(minmax.split(',')[1]) plt.scatter(points[:,0], points[:,1], c=points[:,2], s=ptsize, cmap=cbarv[0],\ marker=ptype, vmin=zminv, vmax=zmaxv) if cbarv[2] == 'horizontal': cbar = plt.colorbar(format=cbarv[1],orientation=cbarv[2]) # From: http://stackoverflow.com/questions/32050030/rotation-of-colorbar-tik-labels-in-matplotlib ticklabels= cbar.ax.get_xticklabels() Nticks = len(ticklabels) ticklabs = [] for itick in range(Nticks): ticklabs.append(ticklabels[itick].get_text()) cbar.ax.set_xticklabels(ticklabs,rotation=90) else: cbar = plt.colorbar(format=cbarv[1],orientation=cbarv[2]) cbar.set_label(gen.latex_text(vname) +' ('+ units_lunits(vunits) + ')') # Legend if legv is not None: my_cmap = plt.cm.get_cmap(cbarv[0]) norm = mpl.colors.Normalize(zminv,zmaxv) Npts = points.shape[0] if legv[0] == 'ptlabel': offx = legv[2] offy = legv[3] for ipt in range(Npts): xpt = points[ipt,0] ypt = points[ipt,1] clv = my_cmap(norm(points[ipt,2])) plt.annotate(gen.latex_text(legv[4+ipt]), xy=(xpt,ypt), color=clv, \ fontsize=legv[1], horizontalalignment="center", xytext=(offx,offy),\ textcoords='offset pixels') elif legv[0] == 'legend': for ipt in range(Npts): xpt = points[ipt,0] ypt = points[ipt,1] clv = my_cmap(norm(points[ipt,2])) plt.plot(xpt, ypt, ',', color=clv, marker=ptype, markersize=ptsize/2., \ label=gen.latex_text(legv[3+ipt])) plt.legend(loc=legv[1], prop={'size':legv[2]}) plt.title(gen.latex_text(figtitle)) if graphlims is not None: plt.xlim(graphlims[0], graphlims[2]) plt.ylim(graphlims[1], graphlims[3]) output_kind(kfig, figname, ifclose) return #pts = np.zeros((10,3), dtype=np.float) #pts[:,0] = np.arange(10,20)*1. #pts[:,1] = np.arange(30,40)*1. #pts[:,2] = np.arange(-5,5)*1. #plot_ptZvals('vals','kgm-2',pts,'.',300, 'values of values', 'seismic', 'cyl,l', 'pdf') def plot_ZQradii(Zmeans, graphtit, kfig, figname): """ Function to plot following radial averages only at exact grid poins Zmeans= radial means radii= values of the taken radii graphtit= title of the graph ('|', for spaces) kfig= kind of figure figname= name of the figure """ fname = 'plot_ZQradii' output_kind(kfig, figname, True) return def plot_vector(xvals, yvals, uvals, vvals, xaxn, yaxn, xaxu ,yaxu, vecfreq, xaxv, \ yaxv, vecoln, veccolor, veclength, vs, windn, wuts, mapv, graphtit, kfig, figname): """ Function to plot vectors xvals= values for the x-axis yvals= values for the y-axis uvals= values for the x-wind vvals= values for the y-wind xaxn= name of the variable for the x-axis yaxn= name of the variable for the y-axis xaxu= units of the variable for the x-axis yaxu= units of the variable for the y-axis vecfreq= [xfreq],[yfreq] frequency of values allong each axis (None, all grid points; 'auto', computed automatically to have 20 vectors along each axis) xaxv= list with the x-axis parameteres [style, format, number and orientation] yaxv= list with the y-axis parameteres [style, format, number and orientation] veccoln= name for the color of the vectors 'singlecol'@[colorn]: all the vectors same color ('auto': for 'red') 'wind'@[colorbar]: color of the vectors according to wind speed sqrt(u^2+v^2) and given [colorbar] '3rdvar'@[colorbar]@[varn]@[units]: color of the vectors according to a 3rd variable (to be added at -v) and given [colorbar] veccolor= color of the vectors veclength= length of the wind vectors: 'singlecol': 'auto', for 9 'wind' and '3rdvar': 'auto' length as wind speed, otherwise fix length vs= minmum and maximum values to plot in shadow or: 'Srange': for full range 'Saroundmean@val': for mean-xtrm,mean+xtrm where xtrm = np.min(mean-min@val,max@val-mean) 'Saroundminmax@val': for min*val,max*val 'Saroundpercentile@val': for median-xtrm,median+xtrm where xtrm = np.min(median-percentile_(val), percentile_(100-val)-median) 'Smean@val': for -xtrm,xtrm where xtrm = np.min(mean-min*@val,max*@val-mean) 'Smedian@val': for -xtrm,xtrm where xtrm = np.min(median-min@val,max@val-median) 'Spercentile@val': for -xtrm,xtrm where xtrm = np.min(median-percentile_(val), percentile_(100-val)-median) windn= name of the wind variable in the graph wuts= units of the wind variable in the graph mapv= map characteristics: [proj],[res] see full documentation: http://matplotlib.org/basemap/ [proj]: projection * 'cyl', cilindric * 'lcc', lambert conformal [res]: resolution: * 'c', crude * 'l', low * 'i', intermediate * 'h', high * 'f', full graphtit= title of the graph ('|', for spaces) kfig= kind of figure figname= name of the figure """ fname = 'plot_vector' dxn = xvals.min() dxx = xvals.max() dyn = yvals.min() dyx = yvals.max() if xaxv[0] == 'pretty': dimxt0 = np.array(gen.pretty_int(dxn,dxx,xaxv[2])) elif xaxv[0] == 'Nfix': dimxt0 = np.arange(dxn,dxx,(dxx-dxn)/(1.*xaxv[2])) elif xaxv[0] == 'Vfix': dimxt0 = np.arange(0,dxx,xaxv[2]) if yaxv[0] == 'pretty': dimyt0 = np.array(gen.pretty_int(dyn,dyx,yaxv[2])) elif yaxv[0] == 'Nfix': dimyt0 = np.arange(dyn,dyx,(dyx-dyn)/(1.*yaxv[2])) elif yaxv[0] == 'Vfix': dimyt0 = np.arange(0,dyx,yaxv[2]) dimxl0 = [] for i in range(len(dimxt0)): dimxl0.append('{:{style}}'.format(dimxt0[i], style=xaxv[1])) dimyl0 = [] for i in range(len(dimyt0)): dimyl0.append('{:{style}}'.format(dimyt0[i], style=yaxv[1])) dimxT0 = variables_values(xaxn)[0] + ' (' + units_lunits(xaxu) + ')' dimyT0 = variables_values(yaxn)[0] + ' (' + units_lunits(yaxu) + ')' dx=xvals.shape[1] dy=xvals.shape[0] # Frequency of vectors if vecfreq is None: xfreq = 1 yfreq = 1 elif vecfreq == 'auto': xfreq = dx/20 yfreq = dy/20 else: xfreq=int(vecfreq.split('@')[0]) yfreq=int(vecfreq.split('@')[1]) # Vector length if veclength == 'auto': vlength = 9 else: vlength = veclength # Colors VecN = vecoln.split('@')[0] if VecN == 'singlecol': if veccolor == 'auto': vcolor = "red" else: vcolor = veccolor elif VecN == 'wind' or VecN == '3rdvar': vcolor = vecoln.split('@')[1] # Changing limits of the colors vsend = graphic_range(vs,veccolor) plt.rc('text', usetex=True) if not mapv is None: lon00 = np.where(xvals[:] < 0., 360. + xvals[:], xvals[:]) lat00 = yvals[:] map_proj=mapv.split(',')[0] map_res=mapv.split(',')[1] nlon = np.min(xvals[::yfreq,::xfreq]) xlon = np.max(xvals[::yfreq,::xfreq]) nlat = np.min(yvals[::yfreq,::xfreq]) xlat = np.max(yvals[::yfreq,::xfreq]) lon2 = xvals[dy/2,dx/2] lat2 = yvals[dy/2,dx/2] print 'lon2:', lon2, 'lat2:', lat2, 'SW pt:', nlon, ',', nlat, 'NE pt:', \ xlon, ',', xlat if map_proj == 'cyl': m = Basemap(projection=map_proj, llcrnrlon=nlon, llcrnrlat=nlat, \ urcrnrlon=xlon, urcrnrlat= xlat, resolution=map_res) elif map_proj == 'lcc': m = Basemap(projection=map_proj, lat_0=lat2, lon_0=lon2, llcrnrlon=nlon, \ llcrnrlat=nlat, urcrnrlon=xlon, urcrnrlat= xlat, resolution=map_res) else: print errormsg print ' ' + fname + ": projection '" + map_proj + "' not ready!!" print ' projections available: cyl, lcc' quit(-1) m.drawcoastlines() meridians = gen.pretty_int(nlon,xlon,5) m.drawmeridians(meridians,labels=[True,False,False,True],color="black") parallels = gen.pretty_int(nlat,xlat,5) m.drawparallels(parallels,labels=[False,True,True,False],color="black") plt.xlabel('W-E') plt.ylabel('S-N') if VecN == 'singlecol': plt.quiver(xvals[::yfreq,::xfreq], yvals[::yfreq,::xfreq], \ uvals[::yfreq,::xfreq], vvals[::yfreq,::xfreq], color=vcolor, pivot='middle') plt.annotate(windn.replace('_','\_') +' (' + units_lunits(wuts) + ')', \ xy=(0.80,-0.15), xycoords='axes fraction', color=vcolor) else: if veclength != 'auto': wind = np.sqrt(uvals**2 + vvals**2) uvals = np.where(wind == 0., 0., uvals) vvals = np.where(wind == 0., 0., vvals) uvals = np.float(veclength)*uvals/wind vvals = np.float(veclength)*vvals/wind plt.quiver(xvals[::yfreq,::xfreq], yvals[::yfreq,::xfreq], \ uvals[::yfreq,::xfreq], vvals[::yfreq,::xfreq], \ veccolor[::yfreq,::xfreq], cmap=plt.get_cmap(vcolor), pivot='middle', \ clim = vsend) # FROM: http://stackoverflow.com/questions/25270661/how-to-set-a-color-bar-range-in-matplotlib cbar = plt.colorbar() if VecN == 'wind': cbar.set_label('$\sqrt{u^{2} + v^{2}}$ (' + units_lunits(wuts) + ')') else: vN = vecoln.split('@')[2] vU = vecoln.split('@')[3] cbar.set_label(vN + ' (' + units_lunits(vU) + ')') plt.annotate(windn.replace('_','\_') +' (' + units_lunits(wuts) + ')', \ xy=(0.80,-0.15), xycoords='axes fraction', color='black') plt.title(graphtit.replace('|',' ').replace('&','\&')) output_kind(kfig, figname, True) return def plot_basins(xvals, yvals, fvals, vecoln, fmtcol, orcol, veccolor, vcolmin, \ vcolmax, windn, wuts, mapv, drawcountry, basinid, graphtit, kfig, figname, fclose): """ Function to plot the rivers from the ORCHIDEE data file `routing.nc' with their upstream flow shaded xvals= values for the x-axis yvals= values for the y-axis fvals= values for the flow (1-8: N, NE, E, ..., NW; 97: sub-basin; 98: small to sea; 99: large to sea) vecoln= name for the color of the vectors (as '3rdvar@[basinsvar]@[varn]@[units]' from plot_vector) fmtcol= format of the labels at the color bar orcol= orientation of the color bar veccolor= color of the vectors windn= name of the wind variable in the graph wuts= units of the wind variable in the graph mapv= map characteristics: [proj],[res] see full documentation: http://matplotlib.org/basemap/ [proj]: projection * 'cyl', cilindric * 'lcc', lambert conformal [res]: resolution: * 'c', crude * 'l', low * 'i', intermediate * 'h', high * 'f', full drawcountry= whether country lines should be plotted or not basinid= whether basins id should be plotted or not graphtit= title of the graph ('|', for spaces) kfig= kind of figure figname= name of the figure fclose= whether figures should be close or not """ fname = 'plot_basins' dx=xvals.shape[1] dy=xvals.shape[0] vlength = 9. # flow direction angle = (fvals[:] - 1)*np.pi/4 uvals = np.where(fvals[:] < 9, np.float(vlength)*np.sin(angle), 0.) vvals = np.where(fvals[:] < 9, np.float(vlength)*np.cos(angle), 0.) # Colors vcolor = vecoln.split('@')[0] plt.rc('text', usetex=True) ddx = np.abs(xvals[dy/2+1,dx/2] - xvals[dy/2,dx/2]) ddy = np.abs(yvals[dy/2,dx/2+1] - yvals[dy/2,dx/2]) fontcharac = {'family': 'serif', 'weight': 'normal', 'size': 3} # Setting up colors for each label # From: http://stackoverflow.com/questions/15235630/matplotlib-pick-up-one-color-associated-to-one-value-in-a-colorbar my_cmap = plt.cm.get_cmap(vcolor) # vcolmin = np.min(veccolor[::yfreq,::xfreq]) # vcolmax = np.max(veccolor[::yfreq,::xfreq]) # vcolmin = 0. # vcolmax = 2500. norm = mpl.colors.Normalize(vcolmin, vcolmax) print 'min col:',vcolmin,'max col:',vcolmax xlabpos = [] ylabpos = [] labels = [] labcol = [] flow = [] flowvals = [] for j in range(0,dy): for i in range(0,dx): if veccolor[j,i] != '--': xlabpos.append(xvals[j,i]) ylabpos.append(yvals[j,i]) labels.append(int(veccolor[j,i])) labcol.append(my_cmap(norm(veccolor[j,i]))) flowvals.append(fvals[j,i]) if not mapv is None: lon00 = np.where(xvals[:] < 0., 360. + xvals[:], xvals[:]) lat00 = yvals[:] map_proj=mapv.split(',')[0] map_res=mapv.split(',')[1] nlon = np.min(xvals[:]) xlon = np.max(xvals[:]) nlat = np.min(yvals[:]) xlat = np.max(yvals[:]) lon2 = xvals[dy/2,dx/2] lat2 = yvals[dy/2,dx/2] print 'lon2:', lon2, 'lat2:', lat2, 'SW pt:', nlon, ',', nlat, 'NE pt:', \ xlon, ',', xlat if map_proj == 'cyl': m = Basemap(projection=map_proj, llcrnrlon=nlon, llcrnrlat=nlat, \ urcrnrlon=xlon, urcrnrlat= xlat, resolution=map_res) elif map_proj == 'lcc': m = Basemap(projection=map_proj, lat_0=lat2, lon_0=lon2, llcrnrlon=nlon, \ llcrnrlat=nlat, urcrnrlon=xlon, urcrnrlat= xlat, resolution=map_res) else: print errormsg print ' ' + fname + ": projection '" + map_proj + "' not ready!!" print ' projections available: cyl, lcc' quit(-1) m.drawcoastlines() drawcountry = True if drawcountry: m.drawcountries() meridians = gen.pretty_int(nlon,xlon,5) m.drawmeridians(meridians,labels=[True,False,False,True],color="black") parallels = gen.pretty_int(nlat,xlat,5) m.drawparallels(parallels,labels=[False,True,True,False],color="black") plt.xlabel('W-E') plt.ylabel('S-N') # if veclength != 'auto': # wind = np.sqrt(uvals**2 + vvals**2) # uvals = np.where(wind == 0., 0., uvals) # vvals = np.where(wind == 0., 0., vvals) # uvals = np.float(veclength)*uvals/wind # vvals = np.float(veclength)*vvals/wind wind = np.sqrt(uvals**2 + vvals**2) uvals = np.where(wind == 0., 0., uvals) vvals = np.where(wind == 0., 0., vvals) uvals = np.float(vlength)*uvals/wind vvals = np.float(vlength)*vvals/wind vecolorvals = veccolor[:] vecolorvals = np.where(vecolorvals < vcolmin, vcolmin - 1, vecolorvals) vecolorvals = np.where(vecolorvals > vcolmax, vcolmax + 1, vecolorvals) plt.quiver(xvals[:], yvals[:], uvals[:], vvals[:], vecolorvals, \ cmap=plt.get_cmap(vcolor), pivot='middle') if orcol == 'horizontal': cbar = plt.colorbar(format=fmtcol,orientation=orcol) # From: http://stackoverflow.com/questions/32050030/rotation-of-colorbar-tik-labels-in-matplotlib ticklabels= cbar.ax.get_xticklabels() Nticks = len(ticklabels) ticklabs = [] for itick in range(Nticks): ticklabs.append(ticklabels[itick].get_text()) cbar.ax.set_xticklabels(ticklabs,rotation=90) else: cbar = plt.colorbar(format=fmtcol,orientation=orcol) vN = vecoln.split('@')[1] vU = vecoln.split('@')[2] cbar.set_label(vN + ' (' + units_lunits(vU) + ')') if basinid: for i in range(len(xlabpos)): plt.text(xlabpos[i]+0.5*ddx, ylabpos[i]+0.95*ddy, \ gen.latex_text(labels[i]), color=labcol[i], fontdict=fontcharac) # Sea-flow for i in range(len(xlabpos)): if flowvals[i] == 97: plt.plot(xlabpos[i], ylabpos[i], 'x', color=labcol[i]) elif flowvals[i] == 98: plt.plot(xlabpos[i], ylabpos[i], '*', color=labcol[i]) elif flowvals[i] == 99: plt.plot(xlabpos[i], ylabpos[i], 'h', color=labcol[i]) plt.annotate(windn.replace('_','\_') +' (' + units_lunits(wuts) + ')', \ xy=(0.80,-0.08), xycoords='axes fraction', color='black') plt.title(gen.latex_text(graphtit)) output_kind(kfig, figname, fclose) return def plot_river_pattern(xvals, yvals, fvals, veccolor, descid, desclon, desclat, \ stn, stlon, stlat, drawcountry, drawbasinid, colordescid, coloriver, colornoriver, \ colorst, stsize, graphtit, mapv, kfig, figname): """ Function to plot vectors xvals= values for the x-axis yvals= values for the y-axis fvals= values for the flow (1-8: N, NE, E, ..., NW; 97: sub-basin; 98: small to sea; 99: large to sea) veccolor= basin id descid= description id , desclon, desclat, mapv= map characteristics: [proj],[res] see full documentation: http://matplotlib.org/basemap/ [proj]: projection * 'cyl', cilindric * 'lcc', lambert conformal [res]: resolution: * 'c', crude * 'l', low * 'i', intermediate * 'h', high * 'f', full drawcountry= whether country lines should be plotted or not drawbasinid= whether basins id should be plotted or not graphtit= title of the graph ('|', for spaces) kfig= kind of figure figname= name of the figure """ fname = 'plot_river_pattern' dx=xvals.shape[1] dy=xvals.shape[0] xmin = np.min(xvals) xmax = np.max(xvals) ymin = np.min(yvals) ymax = np.max(yvals) # flow direction plt.rc('text', usetex=True) ddx = np.abs(xvals[dy/2+1,dx/2] - xvals[dy/2,dx/2]) ddy = np.abs(yvals[dy/2,dx/2+1] - yvals[dy/2,dx/2]) fontcharac = {'family': 'serif', 'weight': 'normal', 'size': 3} xlabpos = [] ylabpos = [] labels = [] labcol = [] flow = [] flowvals = [] xtrack = [] ytrack = [] colortrack = [] trackid = [] stnlL = [] stlonlL = [] stlatlL = [] # Setting up colors for each label # From: http://stackoverflow.com/questions/15235630/matplotlib-pick-up-one-color-associated-to-one-value-in-a-colorbar my_cmap = plt.cm.get_cmap(colordescid) vcolmin = np.min(descid) vcolmax = np.max(descid) norm = mpl.colors.Normalize(vcolmin, vcolmax) # Vector angles lengthtrac = np.float(xvals[0,1] - xvals[0,0]) lengthtrac2 = lengthtrac*np.sqrt(2.) for j in range(0,dy): for i in range(0,dx): if veccolor[j,i] != '--': # ibeg = xvals[j,i]-lengthtrac/2. # jbeg = yvals[j,i]-lengthtrac/2. ibeg = xvals[j,i] jbeg = yvals[j,i] labels.append(int(veccolor[j,i])) flowvals.append(fvals[j,i]) angle = (fvals[j,i] - 1)*np.pi/4 if gen.searchInlist([2,4,6,8], fvals[j,i]): iend = ibeg + lengthtrac2*np.sin(angle) jend = jbeg + lengthtrac2*np.cos(angle) elif gen.searchInlist([1,3,5,7], fvals[j,i]): iend = ibeg + lengthtrac*np.sin(angle) jend = jbeg + lengthtrac*np.cos(angle) else: ibeg = xvals[j,i] jbeg = yvals[j,i] iend = None jend = None xlabpos.append(ibeg) ylabpos.append(jbeg) xtrack.append(ibeg) xtrack.append(iend) xtrack.append(None) ytrack.append(jbeg) ytrack.append(jend) ytrack.append(None) if len(desclon.shape) == 2: difflonlat = np.sqrt((desclon-xvals[j,i])**2 + (desclat-yvals[j,i])**2) mindiffLl = np.min(difflonlat) ilatlon = gen.index_mat(difflonlat, mindiffLl) else: ilatlon = np.zeros((2), dtype=int) difflon = np.abs(desclon - xvals[j,i]) mindiffl = np.min(difflon) ilatlon[1] = gen.index_vec(difflon,mindiffl) difflat = np.abs(desclat - yvals[j,i]) mindiffL = np.min(difflat) ilatlon[0] = gen.index_vec(difflat,mindiffL) if descid.mask[ilatlon[0],ilatlon[1]]: labcol.append(colornoriver) colortrack.append(colornoriver) else: if veccolor[j,i] != 6: labcol.append(colornoriver) colortrack.append(colornoriver) # print 'Lluis: veccol:', veccolor[j,i], 'mindiffl', mindiffl,'mindiffL:',mindiffL else: # print 'Lluis right! mindiffl', mindiffl,'mindiffL:',mindiffL labcol.append(coloriver) colortrack.append(my_cmap(norm(descid[ilatlon[0],ilatlon[1]]))) trackid.append(descid[ilatlon[0],ilatlon[1]]) totvals = len(flowvals) if not mapv is None: lon00 = np.where(xvals[:] < 0., 360. + xvals[:], xvals[:]) lat00 = yvals[:] map_proj=mapv.split(',')[0] map_res=mapv.split(',')[1] nlon = np.min(xvals) xlon = np.max(xvals) nlat = np.min(yvals) xlat = np.max(yvals) lon2 = xvals[dy/2,dx/2] lat2 = yvals[dy/2,dx/2] print 'lon2:', lon2, 'lat2:', lat2, 'SW pt:', nlon, ',', nlat, 'NE pt:', \ xlon, ',', xlat if map_proj == 'cyl': m = Basemap(projection=map_proj, llcrnrlon=nlon, llcrnrlat=nlat, \ urcrnrlon=xlon, urcrnrlat= xlat, resolution=map_res) elif map_proj == 'lcc': m = Basemap(projection=map_proj, lat_0=lat2, lon_0=lon2, llcrnrlon=nlon, \ llcrnrlat=nlat, urcrnrlon=xlon, urcrnrlat= xlat, resolution=map_res) else: print errormsg print ' ' + fname + ": projection '" + map_proj + "' not ready!!" print ' projections available: cyl, lcc' quit(-1) m.drawcoastlines() drawcountry = True if drawcountry: m.drawcountries() meridians = gen.pretty_int(nlon,xlon,5) m.drawmeridians(meridians,labels=[True,False,False,True],color="black") parallels = gen.pretty_int(nlat,xlat,5) m.drawparallels(parallels,labels=[False,True,True,False],color="black") plt.xlabel('W-E') plt.ylabel('S-N') j = 0 for i in range(len(xlabpos)): plt.plot(xtrack[j:j+2], ytrack[j:j+2], color=colortrack[i]) j = j + 3 # Sea-flow for i in range(len(xlabpos)): if flowvals[i] == 97: plt.plot(xlabpos[i], ylabpos[i], 'x', color=colortrack[i]) elif flowvals[i] == 98: plt.plot(xlabpos[i], ylabpos[i], '*', color=colortrack[i]) elif flowvals[i] == 99: plt.plot(xlabpos[i], ylabpos[i], 'h', color=colortrack[i]) plt.xlim(xmin,xmax) plt.ylim(ymin,ymax) if drawbasinid: for i in range(len(xlabpos)): plt.text(xlabpos[i]+0.05*lengthtrac, ylabpos[i]+0.05*lengthtrac, labels[i], \ color=labcol[i], fontdict=fontcharac) # plt.text(xlabpos[i]+0.1*lengthtrac, ylabpos[i]+0.1*lengthtrac, trackid[i], \ # color=colortrack[i], fontdict=fontcharac) # plt.text(xlabpos[i]+0.1*lengthtrac, ylabpos[i]+0.1*lengthtrac, str(flowvals[i]), \ # color=colortrack[i], fontdict=fontcharac) for ist in range(len(stlon)): if stlon[ist] > xmin and stlon[ist] < xmax and stlat[ist] > ymin and stlat[ist] < ymax: stname = '*' for ic in range(len(stn[ist,:])): stname = stname + stn[ist,ic] # plt.annotate(stname, xy=(stlon[ist],stlat[ist]), color=colorst, ) plt.text(stlon[ist], stlat[ist], stname, color=colorst, fontsize=stsize) # cbar = plt.colorbar() plt.title(graphtit.replace('&','\&')) output_kind(kfig, figname, True) return def var_3desc(ovar): """ Function to provide std_name, long_name and units from an object variable ovar= object variable """ fname = 'var_desc' varattrs = ovar.ncattrs() if searchInlist(varattrs,'std_name'): stdn = ovar.getncattr('std_name') else: vvalues = variables_values(ovar._name) stdn = vvalues[1] if searchInlist(varattrs,'long_name'): lonn = ovar.getncattr('long_name') else: lonn = vvalues[4].replace('|',' ') if searchInlist(varattrs,'units'): un = ovar.getncattr('units') else: un = vvalues[5] return stdn, lonn, un def plot_river_desc(lons, lats, rns, rss, rus, ros, bcolor, ucolor, uuts, mapv, \ graphtit, kfig, lloc, figname, closef): """ Function to plot rivers from 'river_desc.nc' ORCDHIEE lons= values for the x-axis lats= values for the y-axis rns= list of the name of the rivers to plot rss= dictionary with the lon,lats of the subbasins of each river rus= dictionary with the lon,lats of the upstream values of each river ros= dictionary with the lon,lats of the outflow points of each river bcolor= color of the lines for the subbasins ucolor= bar color for the upstreams uuts= units of the upstream mapv= map characteristics: [proj],[res] see full documentation: http://matplotlib.org/basemap/ [proj]: projection * 'cyl', cilindric * 'lcc', lambert conformal [res]: resolution: * 'c', crude * 'l', low * 'i', intermediate * 'h', high * 'f', full graphtit= title of the graph ('|', for spaces) lloc= location of the legend (0, automatic) 1: 'upper right', 2: 'upper left', 3: 'lower left', 4: 'lower right', 5: 'right', 6: 'center left', 7: 'center right', 8: 'lower center', 9: 'upper center', 10: 'center' kfig= kind of figure figname= name of the figure closef= whether should be closed or not """ fname = 'plot_basins' colvalues, linekinds, pointkinds, lwidths, psizes = ColorsLinesPointsStyles( \ len(rns), bcolor, ['-'], ['.'], [1.], [1.], None) dx=lons.shape[1] dy=lats.shape[0] plt.rc('text', usetex=True) nlon = np.min(lons) xlon = np.max(lons) nlat = np.min(lats) xlat = np.max(lats) dlon = xlon - nlon dlat = xlat - nlat # Making bigger the area to map nlon = np.min(lons)-dlon*0.1 xlon = np.max(lons)+dlon*0.1 nlat = np.min(lats)-dlat*0.1 xlat = np.max(lats)+dlat*0.1 plt.xlim(nlon,xlon) plt.ylim(nlat,xlat) if not mapv is None: lon00 = np.where(lons[:] < 0., 360. + lons[:], lons[:]) lat00 = lats[:] map_proj=mapv.split(',')[0] map_res=mapv.split(',')[1] lon2 = (nlon + xlon)/2. lat2 = (nlat + xlat)/2. print 'lon2:', lon2, 'lat2:', lat2, 'SW pt:', nlon, ',', nlat, 'NE pt:', \ xlon, ',', xlat if map_proj == 'cyl': m = Basemap(projection=map_proj, llcrnrlon=nlon, llcrnrlat=nlat, \ urcrnrlon=xlon, urcrnrlat= xlat, resolution=map_res) elif map_proj == 'lcc': m = Basemap(projection=map_proj, lat_0=lat2, lon_0=lon2, llcrnrlon=nlon, \ llcrnrlat=nlat, urcrnrlon=xlon, urcrnrlat= xlat, resolution=map_res) else: print errormsg print ' ' + fname + ": projection '" + map_proj + "' not ready!!" print ' projections available: cyl, lcc' quit(-1) m.drawcoastlines() meridians = gen.pretty_int(nlon,xlon,5) m.drawmeridians(meridians,labels=[True,False,False,True],color="black") parallels = gen.pretty_int(nlat,xlat,5) m.drawparallels(parallels,labels=[False,True,True,False],color="black") plt.xlabel('W-E') plt.ylabel('S-N') umin = 10.e20 umax = -umin for rn in rns: nrns = np.min(rus[rn]) xrns = np.max(rus[rn]) if umin > nrns: umin = nrns if umax < xrns: umax = xrns i = 0 for rn in rns: plt.pcolormesh(lons, lats, rus[rn], vmin=umin, vmax=umax, \ cmap=plt.get_cmap(ucolor), norm=matplotlib.colors.LogNorm()) # plt.pcolormesh(lons, lats, rss[rn], cmap=plt.get_cmap(ucolor)) if rn == rns[0]: cbar = plt.colorbar() riverarea = rss[rn] riverarea.mask = ma.nomask rarea = np.where(riverarea == 999999999, -5, riverarea) rarea = np.where(rarea > 0, 1, 0) plt.contour(lons, lats, rarea, levels = [0.], colors=colvalues[i], \ linewidths=1.5) oflow = ros[rn] plt.plot(oflow[0], oflow[1], 'h', color=colvalues[i], label=rn) # plt.annotate(rn, xy=(0., i*0.05), xycoords='axes fraction', color=colvalues[i]) i = i+1 # Attempts to plot sub-basins # Gradient subbasins (not working) # gradriver = np.zeros((dy,dx), dtype=int) # for j in range(dy-2): # for i in range(dx-2): # gradriver[j,i] = riverarea[j,i+1]-riverarea[j,i]+riverarea[j+1,i]- \ # riverarea[j,i] # garea = np.where(gradriver != 0, 1, gradriver) # print garea # plt.contour(lons, lats, garea, levels = [0.], colors='red', linewidths=1.) # Not working # subbasins = np.sort(np.unique(rarea)) # for subb in subbasins: # if subb > 0.: # sarea = np.where(rarea != subb, 0, rarea) # plt.contour(lons, lats, sarea, levels = [1.], colors='gray', linewidths=1.) cbar.set_label('upstream (' + units_lunits(uuts) + ')') plt.legend(loc=lloc) # plt.annotate(windn.replace('_','\_') +' (' + units_lunits(wuts) + ')', \ # xy=(0.80,-0.15), xycoords='axes fraction', color='black') plt.title(gen.latex_text(graphtit)) output_kind(kfig, figname, closef) return def plot_vertical_lev(vertz, vertp, zlog, dzlog, plog, dplog, gtit, kfig, lloc, \ lsize, fclose): """ plotting vertical levels distribution plot_vertical_lev(vertz, gtit, kfig, lloc) vertz= distribution of vertical heights [z] vertp= distribution of vertical pressures [Pa] zlog: to use logarithmic scale on the height axis ('true/false') dzlog: to use logarithmic scale on the difference of height between levels axis ('true/false') plog: to use logarithmic scale on the pressure axis ('true/false') pzlog: to use logarithmic scale on the difference of pressure between levels axis ('true/false') gtit= title of the graph ('!' for spaces) kfig= kind of figure (jpg, pdf, png) lloc= location of the legend (0, automatic) 1: 'upper right', 2: 'upper left', 3: 'lower left', 4: 'lower right', 5: 'right', 6: 'center left', 7: 'center right', 8: 'lower center', 9: 'upper center', 10: 'center' kfig= kind of figure lsize: font-size of the labels in legend fclose: whether figures shoul be closed or not """ fname = 'plot_vertical_lev' figname = 'vertical_lev' if vertz == 'h': print fname + '_____________________________________________________________' print plot_vertical_lev.__doc__ quit() Nlev = len(vertz) dvertz = vertz[1:Nlev] - vertz[0:Nlev-1] # From: http://stackoverflow.com/questions/14762181/adding-a-y-axis-label-to-secondary-y-axis-in-matplotlib plt.rc('text', usetex=True) # Height plot ## if vertp is not None: fig, (ax1, ax3) = plt.subplots(nrows=2, ncols=1, sharex=True) else: fig, ax1 = plt.subplots() ax2 = ax1.twinx() plt.xlim(0,Nlev) l1 = ax1.plot(range(Nlev), vertz, 'r-x', label='height') l2 = ax2.plot(range(1,Nlev), dvertz, 'b-x', label='dheight') listz = np.where(vertz == 0., 10000., vertz) # ax1.set_xlabel('level (\#)') ax1.set_ylabel('height ($m$)', color='r') ax1.set_ylim(np.min([1., np.max([0.,np.min(listz)]) ]), np.max(vertz)) ax1.grid() ax2.set_ylabel('difference between levels ($m$)', color='b') #plt.legend(['height', 'dheight'], loc=lloc, prop={'size':lsize}) if vertp is not None: ax1.set_title('height') if zlog: ax1.set_yscale('log') if dzlog: ax2.set_yscale('log') # Pressure plot ## if vertp is not None: Nlev = len(vertp) dvertp = vertp[0:Nlev-1] - vertp[1:Nlev] ax4 = ax3.twinx() l3 = ax3.plot(range(Nlev), vertp, 'r-o', label='pressure') l4 = ax4.plot(range(1,Nlev), dvertp, 'b-o', label='dpressure') ax3.set_xlim(0, Nlev) ax3.set_xlabel('level (\#)') ax3.set_ylabel('pressure ($Pa$)', color='r') ax3.set_ylim(np.min(vertp), np.max(vertp)) ax3.grid() ax4.set_ylabel('difference between levels ($Pa$)', color='b') #plt.legend(['pressure','dpressure'], loc=lloc, prop={'size':lsize}) if plog: ax3.set_yscale('log') if dplog: ax4.set_yscale('log') if vertp is not None: fig.suptitle(gtit) ax3.set_title('pressure') else: plt.title(gen.latex_text(gtit)) output_kind(kfig, figname, fclose) return def plot_subbasin(subname, lons, lats, rsf, rLlf, rof, rcolors, mapv, basinwidth, \ drawsubid, graphtit, kfig, lloc, figname, drivers, fclose): """ Function to plot a reiver basin from a given point of its discharge from 'river_desc.nc' ORCDHIEE after `subbasin' [subname]= name of the subbasin [lons]= values for the x-axis [lats]= values for the y-axis [rsf]= list of the name of the sub-flows to plot [rLlf]= dictionary with the lat,lon of the subflows [rof]= dictionary with the outflows of the subflows [rcolors]= base of colors of the lines for the subflows (first level) [mapv]= map characteristics: [proj],[res] see full documentation: http://matplotlib.org/basemap/ [proj]: projection * 'cyl', cilindric * 'lcc', lambert conformal [res]: resolution: * 'c', crude * 'l', low * 'i', intermediate * 'h', high * 'f', full [basinwidth]= with of the lines of the basin [drawsubid]= wehther sub-flow ids should be plot or not [graphtit]= title of the graph ('|', for spaces) [lloc]= location of the legend (0, automatic) 1: 'upper right', 2: 'upper left', 3: 'lower left', 4: 'lower right', 5: 'right', 6: 'center left', 7: 'center right', 8: 'lower center', 9: 'upper center', 10: 'center' kfig= kind of figure [figname]= name of the figure [drivers]= whether river basins from python's data-base should be added or not [fclose]= whether figure should be closed or not """ fname = 'plot_subbasin' dx=lons.shape[1] dy=lats.shape[0] lengthtrac = np.float(lons[0,1] - lons[0,0]) lengthtrac2 = lengthtrac*np.sqrt(2.) ddx = np.abs(lons[dy/2+1,dx/2] - lons[dy/2,dx/2]) ddy = np.abs(lats[dy/2,dx/2+1] - lats[dy/2,dx/2]) fontcharac = {'family': 'serif', 'weight': 'normal', 'size': 10} subhr = gen.chainSnumHierarchy(rsf) # Getting colors Nsubs = len(rsf) maxNgrids = -1 collev = {} if rcolors is None: # 1st level colors from colorsauto for isub in range(subhr.xlevs[1]): collev[gen.num_chainSnum(isub+1)] = gen.colhex_dec(colorsauto[isub]) else: if len(rcolors) != subhr.Llev1: print errormsg print ' ' + fname + ': number of first subbasins:', subhr.Llev1, \ 'and number of provided colors:', len(rcolors), 'differ !!' print ' provided colors:', rcolors quit(-1) for isub in range(subhr.xlevs[1]): collev[gen.num_chainSnum(isub+1)] = rcolors[isub] # All the colors should finish white... endcol = [1., 1., 1.] # endcol = [0.9, 0.9, 0.9] colorsub = {} xlabpos = [] ylabpos = [] xtrack = [] ytrack = [] colortrack = [] outflows = [] for isub in rsf: levs = gen.num_split(isub) Nlevs = len(levs) if Nlevs == 1: begcol = [0., 0., 0.] else: begcol = collev[levs[1]] for ilev in range(2,Nlevs): # We do not want a last white value... if Nlevs < subhr.Nlevs: maxNcol = subhr.xlevs[ilev]+1 else: maxNcol = subhr.xlevs[ilev]+1 colors = gen.color_deg([begcol, endcol], maxNcol, 'std') begcol = colors[1:4,gen.chainSnum_num(levs[ilev])-1] colorsub[isub] = tuple(begcol) # Avoiding too clear colors cols = colorsub[isub] if (cols[0] >= 0.95)*(cols[1] >= 0.95)*(cols[2] >= 0.95): print warnmsg print ' ' + fname + ': avoiding to clear color:', colorsub[isub], '!!' maxcol = np.max(cols) imaxcol = gen.index_vec(cols, maxcol) clear = np.ones((3), dtype=np.float)*0.9 clear[imaxcol] = 0.95 print ' keeping it clear:', clear colorsub[isub] = tuple(clear) Llfs = rLlf[isub] outfs = rof[isub] for igrid in range(len(outfs)): Llf = Llfs[igrid] ibeg = Llf[1] jbeg = Llf[0] outflows.append(outfs[igrid]) angle = (outfs[igrid] - 1)*np.pi/4 if gen.searchInlist([2,4,6,8], outfs[igrid]): iend = ibeg + lengthtrac2*np.sin(angle) jend = jbeg + lengthtrac2*np.cos(angle) elif gen.searchInlist([1,3,5,7], outfs[igrid]): iend = ibeg + lengthtrac*np.sin(angle) jend = jbeg + lengthtrac*np.cos(angle) else: ibeg = xvals[j,i] jbeg = yvals[j,i] iend = None jend = None xtrack.append(ibeg) xtrack.append(iend) xtrack.append(None) ytrack.append(jbeg) ytrack.append(jend) ytrack.append(None) colortrack.append(colorsub[isub]) xlabpos.append(ibeg) ylabpos.append(jbeg) plt.rc('text', usetex=True) nlon = np.min(xlabpos) xlon = np.max(xlabpos) nlat = np.min(ylabpos) xlat = np.max(ylabpos) dlon = xlon - nlon dlat = xlat - nlat # Making bigger the area to map # nlon = nlon-dlon-lengthtrac2 # xlon = xlon+dlon+lengthtrac2 # nlat = nlat-dlat-lengthtrac2 # xlat = xlat+dlat+lengthtrac2 nlon = nlon-2.*lengthtrac*dlon/np.abs(dlon) xlon = xlon+2.*lengthtrac*dlon/np.abs(dlon) nlat = nlat-2.*lengthtrac*dlat/np.abs(dlat) xlat = xlat+2.*lengthtrac*dlat/np.abs(dlat) plt.xlim(nlon,xlon) plt.ylim(nlat,xlat) if not mapv is None: lon00 = np.where(lons[:] < 0., 360. + lons[:], lons[:]) lat00 = lats[:] map_proj=mapv.split(',')[0] map_res=mapv.split(',')[1] lon2 = (nlon + xlon)/2. lat2 = (nlat + xlat)/2. print 'lon2:', lon2, 'lat2:', lat2, 'SW pt:', nlon, ',', nlat, 'NE pt:', \ xlon, ',', xlat if map_proj == 'cyl': m = Basemap(projection=map_proj, llcrnrlon=nlon, llcrnrlat=nlat, \ urcrnrlon=xlon, urcrnrlat= xlat, resolution=map_res) elif map_proj == 'lcc': m = Basemap(projection=map_proj, lat_0=lat2, lon_0=lon2, llcrnrlon=nlon, \ llcrnrlat=nlat, urcrnrlon=xlon, urcrnrlat= xlat, resolution=map_res) else: print errormsg print ' ' + fname + ": projection '" + map_proj + "' not ready!!" print ' projections available: cyl, lcc' quit(-1) m.drawcoastlines() meridians = gen.pretty_int(nlon,xlon,5) m.drawmeridians(meridians,labels=[True,False,False,True],color="black") parallels = gen.pretty_int(nlat,xlat,5) m.drawparallels(parallels,labels=[False,True,True,False],color="black") plt.xlabel('W-E') plt.ylabel('S-N') if drivers: m.drawrivers(color='blue') j = 0 for i in range(len(xtrack)/3): plt.plot(xtrack[j:j+2], ytrack[j:j+2], color=colortrack[i], linewidth=basinwidth) j = j + 3 # Sea-flow for i in range(len(outflows)): if outflows[i] == 97: plt.plot(xlabpos[i], ylabpos[i], 'x', color=colorsub[i]) elif outflows[i] == 98: plt.plot(xlabpos[i], ylabpos[i], '*', color=colorsub[i]) elif outflows[i] == 99: plt.plot(xlabpos[i], ylabpos[i], 'h', color=colorsub[i]) if drawsubid: for i in range(len(xlabpos)): plt.text(xlabpos[i]+0.05*lengthtrac, ylabpos[i]+0.05*lengthtrac, rsf[i], \ color=colorsub[rsf[i]], fontdict=fontcharac) plt.title(gen.latex_text(graphtit)) output_kind(kfig, figname, fclose) return def plot_2lines(valsA, valsB, valsaxisA, valsaxisB, rangeA, rangeB, rangeaxis, \ axisvals, varns, varus, cols, wdths, styls, szmks, marks, gtitle, axisn, gloc, \ sloc, fign, figk, ifclose): """ Function to plot two lines in different axes (x/x2 or y/y2) valsA= values to be plotted on axis x or y valsB= values to be plotted on axis x2 or y2 valsaxisA= values at the common axis for valsA valsaxisB= values at the common axis for valsB rangeA= range of values for valsA rangeB= range of values for valsB rangeaxis= range of values for the common axis axisvals= which is the axis to plot the values ('x' or 'y') varns= names of the variables in the plot varus= units of the variables cols= list with color names of the lines for the variables wdths= list with widths of the lines for the variables styls= list with the styles of the lines szmks= list with the size of the markers of the lines marks= list with the markers of the lines gtitle= title of the figure axisn= label in the figure of the common axis gloc= location of the legend gsiz= fontsize of the legend fign= name of the figure figk= kind of figure ifclose: Whether figure should be finished or not """ fname = 'plot_2lines' if axisvals == 'x': titX = axisn titX2 = axisn titY = varns[0] + ' (' + varus[0] + ')' titY2 = varns[1] + ' (' + varus[1] + ')' xmin = rangeaxis[0] xmax = rangeaxis[1] xmin2 = rangeaxis[0] xmax2 = rangeaxis[1] ymin = rangeA[0] ymax = rangeA[1] ymin2 = rangeB[0] ymax2 = rangeB[1] else: titX = varns[0] + ' (' + varus[0] + ')' titX2 = varns[1] + ' (' + varus[1] + ')' titY = axisn titY2 = axisn xmin = rangeA[0] xmax = rangeA[1] xmin2 = rangeB[0] xmax2 = rangeB[1] ymin = rangeaxis[0] ymax = rangeaxis[1] ymin2 = rangeaxis[0] ymax2 = rangeaxis[1] # From: http://matplotlib.org/examples/api/two_scales.html fig, ax1 = plt.subplots() plt.rc('text', usetex=True) # Plotting lines il=0 if axisvals == 'x': lA, = ax1.plot(valsaxisA, valsA, styls[il], marker=marks[il], \ linewidth=wdths[il], markersize=szmks[il], label=varns[il], color=cols[il]) ax1.set_xlabel(titX, color='black') ax1.set_ylabel(titY, color=cols[il]) ax1.set_xlim(xmin,xmax) ax1.set_ylim(ymin,ymax) ax2 = ax1.twinx() il = il + 1 lB, = ax2.plot(valsaxisB, valsB, styls[il], marker=marks[il], \ linewidth=wdths[il], markersize=szmks[il], label=varns[il], color=cols[il]) ax2.set_ylabel(titY2, color=cols[il]) ax2.set_ylim(ymin2,ymax2) ax2.set_xlim(xmin,xmax) titleloc = (0.5,1.) else: lA, = ax1.plot(valsA, valsaxisA, styls[il], marker=marks[il], \ linewidth=wdths[il], markersize=szmks[il], label=varns[il], color=cols[il]) ax1.set_xlabel(titX, color=cols[il]) ax1.set_ylabel(titY, color='black') ax1.set_xlim(xmin,xmax) ax1.set_ylim(ymin,ymax) ax2 = ax1.twiny() il = il + 1 lB, = ax2.plot(valsB, valsaxisB, styls[il], marker=marks[il], \ linewidth=wdths[il], markersize=szmks[il], label=varns[il], color=cols[il]) ax2.set_xlabel(titX2, color=cols[il]) ax2.set_xlim(xmin2,xmax2) ax2.set_ylim(ymin,ymax) titleloc = (0.5,1.075) graphtit = gen.latex_text(gtitle) plt.title(graphtit,position=titleloc) # plt.legend([lA, lB], loc=gloc, prop={'size':gsize}) output_kind(figk, fign, ifclose) return def plot_2lines_time(valsA, valsB, valsaxisA, valsaxisB, rangeA, rangeB, valstaxis, \ labelstaxis, taxis, varns, varus, cols, wdths, styls, szmks, marks, gtitle, axisn, \ gloc, gsize, fign, figk, ifclose): """ Function to plot two time-lines in different axes (x/x2 or y/y2) valsA= values to be plotted on axis x or y valsB= values to be plotted on axis x2 or y2 valsaxisA= values at the common axis for valsA valsaxisB= values at the common axis for valsB rangeA= range of values for valsA rangeB= range of values for valsB valstaxis= values for the tick in the time-axis labelstaxis= labels for the tick in the time-axis taxis= which is the axis for the time values ('x' or 'y') varns= names of the variables in the plot varus= units of the variables cols= list with color names of the lines for the variables wdths= list with widths of the lines for the variables styls= list with the styles of the lines szmks= list with the size of the markers of the lines marks= list with the markers of the lines gtitle= title of the figure axisn= label in the figure of the time axis gloc= location of the legend gsiz= fontsize of the legend fign= name of the figure figk= kind of figure ifclose: Whether figure should be finished or not """ fname = 'plot_2lines_time' if taxis == 'x': titX = axisn titX2 = axisn titY = varns[0] + ' (' + varus[0] + ')' titY2 = varns[1] + ' (' + varus[1] + ')' xmin = np.min(valstaxis) xmax = np.max(valstaxis) ymin = rangeA[0] ymax = rangeA[1] ymin2 = rangeB[0] ymax2 = rangeB[1] else: titX = varns[0] + ' (' + varus[0] + ')' titX2 = varns[1] + ' (' + varus[1] + ')' titY = axisn titY2 = axisn xmin = rangeA[0] xmax = rangeA[1] xmin2 = rangeB[0] xmax2 = rangeB[1] ymin = np.min(valstaxis) ymax = np.max(valstaxis) # From: http://matplotlib.org/examples/api/two_scales.html fig, ax1 = plt.subplots() plt.rc('text', usetex=True) # Plotting lines il=0 if taxis == 'x': lA, = ax1.plot(valsaxisA, valsA, styls[il], marker=marks[il], \ linewidth=wdths[il], markersize=szmks[il], label=varns[il], color=cols[il]) ax1.set_xlabel(titX, color='black') ax1.set_ylabel(titY, color=cols[il]) ax1.set_xlim(xmin,xmax) ax1.set_ylim(ymin,ymax) ax1.set_xticks(valstaxis) ax1.set_xticklabels(labelstaxis) ax2 = ax1.twinx() il = il + 1 lB, = ax2.plot(valsaxisB, valsB, styls[il], marker=marks[il], \ linewidth=wdths[il], markersize=szmks[il], label=varns[il], color=cols[il]) ax2.set_ylabel(titY2, color=cols[il]) ax2.set_ylim(ymin2,ymax2) ax2.set_xlim(xmin,xmax) ax2.set_xticks(valstaxis) ax2.set_xticklabels(labelstaxis) titleloc = (0.5,1.) else: lA, = ax1.plot(valsA, valsaxisA, styls[il], marker=marks[il], \ linewidth=wdths[il], markersize=szmks[il], label=varns[il], color=cols[il]) ax1.set_xlabel(titX, color=cols[il]) ax1.set_ylabel(titY, color='black') ax1.set_xlim(xmin,xmax) ax1.set_ylim(ymin,ymax) ax1.set_yticks(valstaxis) ax1.set_yticklabels(labelstaxis) ax2 = ax1.twiny() il = il + 1 lB, = ax2.plot(valsB, valsaxisB, styls[il], marker=marks[il], \ linewidth=wdths[il], markersize=szmks[il], label=varns[il], color=cols[il]) ax2.set_xlabel(titX2, color=cols[il]) ax2.set_xlim(xmin2,xmax2) ax2.set_ylim(ymin,ymax) ax2.set_yticks(valstaxis) ax2.set_yticklabels(labelstaxis) titleloc = (0.5,1.075) graphtit = gen.latex_text(gtitle) plt.title(graphtit,position=titleloc) # plt.legend([lA, lB], loc=gloc, prop={'size':gsize}) output_kind(figk, fign, ifclose) return def plot_WindRose(ang, speed, dime, lpvals, thetalabs, windu, titimg, kfig, figname, \ close, origfilen, outputfile=False, ev=None, eunit=None): """ Function to plot a wind rose (from where the dinw blows) ang= angle of the winds speed= speed of the winds Nang= number of angles to split the total circumference Nspeed= number of speed sections to split the wind distribution maxspeed= maximum wind speed to be plotted dime= number of winds to plot lpvals= values to configure the kind of Wind Rose to plot lpvals[0]: kind of Wind Rose lpvals[1]: specie of kind of Wind Rose lpvals[>=2]: specific values for the specie Wind Rose 'anglespeedfreq';[Nang];[Nspeed];[maxspeed];[cbar];[maxfreq] grid of frequencies of each angle and speed following a given discretization 'linepoint';[kind];[val1];[...;[valN]]: consecutive (time, height, level, ...) line-point angle and speed values 'multicol';[extravarn];[line];[marker];[colbar] 'multicoltime';[extravarn];[line];[marker];[colbar];[timekind];[timefmt];[timelabel] 'singlecol';[line];[marker];[col] 'scatter';[kind];[val1];[...;[valN]]: a cross for each wind at different values (time, height, level, ...) 'multicol';[extravarn];[marker];[colbar] 'multicoltime';[extravarn];[line];[marker];[colbar];[timekind];[timefmt];[timelabel] 'singlecol';[marker];[col] windu= units of the wind speed thetalabs= kind of labels for the angles of the wind-rose 'cardianals': Following combinations of 'N', 'E', 'S', 'W' according to Nang titimg= title of the image kfig= kind of figure figname= name of the figure close= wether figure has to be closed or not origfilen= Name of the file from which the data cames from outputfile= wether file with wind and angle frequencies has to be created (only valid for 'anglespeedfreq') ev= extra values (for certain Wind Roses: 'linepoint/scatter' 'multicol' & 'multicoltime') eunits= units of the extravalues (for certain Wind Roses) """ fname = 'plot_WindRose' if lpvals[0] == 'anglespeedfreq': # Computing statistics Nang = gen.auto_val(lpvals[1], 8) Nspeed = gen.auto_val(lpvals[2], 8) maxspeed = gen.auto_val(lpvals[3], 40.) freqcbar = gen.auto_val(lpvals[4], 'spectral_r') maxfreq = lpvals[5] dang = 2.*np.pi / (Nang) dang2 = dang/2. nspeed = 0. xspeed = maxspeed dspeed = maxspeed/(Nspeed) # Adding one extra partition for the last range #Nang = Nang + 1 Nspeed = Nspeed + 1 # Angle localized angfound = np.zeros((dime), dtype=bool) # Angles's distirbution angdistrib = np.zeros((Nang), dtype=np.float) # Wind speed distirbution following angle ang_speeddistrib = {} # Wind speed distirbution following angle & speed speedang_speeddistrib = {} for it in range(dime): for iang in range(Nang): # initial/ending of the angle section iasec = iang*dang - dang/2. easec = iasec + dang if ang[it] >= iasec and ang[it] < easec: Siang = str(iang) angfound[it] = True angdistrib[iang] = angdistrib[iang] + 1 if ang_speeddistrib.has_key(iang): speeds = ang_speeddistrib[iang] ang_speeddistrib[iang] = speeds + [speed[iang]] else: ang_speeddistrib[iang] = [speed[it]] # initial/ending of the speed section for ispd in range(Nspeed): issec = ispd*dspeed - dspeed/2. essec = issec + dspeed if speed[it] >= issec and speed[it] < essec: Siaspd = Siang + '_' + str(ispd) if speedang_speeddistrib.has_key(Siaspd): speedangs = speedang_speeddistrib[Siaspd] speedang_speeddistrib[Siaspd]= speedangs + [speed[it]] else: speedang_speeddistrib[Siaspd]= [speed[it]] break if not angfound[it]: print warnmsg print 'angle:',ang[it],': not located within:', dang*np.arange(Nang)-\ dang/2. lkind = lpvals[1] # Getting time values and ticks if lkind == 'multicoltime': if lpvals[0] == 'linepoint': timekind = lpvals[7] timefmt = lpvals[8] elif lpvals[0] == 'scatter': timekind = lpvals[6] timefmt = lpvals[7] timepos, timelabels = CFtimes_plot(ev, eunit, timekind, timefmt) if lpvals[0] == 'anglespeedfreq': # Distribution of Frequencies TOTwinds = 0 freqs = np.zeros((Nspeed,Nang), dtype=np.float) for ian in range(Nang): for isp in range(Nspeed): Siaspd = str(ian) + '_' + str(isp) if speedang_speeddistrib.has_key(Siaspd): Nwind = len(speedang_speeddistrib[Siaspd]) freqs[isp,ian] = Nwind TOTwinds = TOTwinds + Nwind if np.sum(freqs) != TOTwinds: print errormsg print 'number of located frequencies:', freqs, 'and number of values:', \ TOTwinds, 'differ!!' quit(-1) # Normalizing freqs = freqs*1./TOTwinds freqs = ma.masked_equal(freqs, 0.) # Filling with zeros up to the highest speed for iang in range(Nang): xfreq = freqs[:,iang].max() if not np.all(freqs.mask[:,iang]): indicesc = gen.multi_index_mat(freqs.mask[:,iang], False) xind = np.max(indicesc) freqs[0:xind+1,iang]= np.where(freqs.mask[0:xind+1,iang], 0., \ freqs[0:xind+1,iang]) if type(maxfreq) == type('s'): if maxfreq == 'auto': maxfreq = freqs.max() # Plot plt.rc('text', usetex=True) ax = plt.subplot(111, projection='polar') # Rosekind # Scatter if lpvals[0] == 'fill': plt.fill_between(ang, speed, 0.) elif lpvals[0] == 'anglespeedfreq': angs = np.arange(Nang,dtype=np.float)*dang - dang/2. spds = np.arange(Nspeed,dtype=np.float)*dspeed - dspeed/2. spds[0] = 0. x, y = gen.lonlat2D(angs,spds) plt.pcolormesh(x, y, freqs, cmap=freqcbar, vmin=0., vmax=maxfreq) cbar = plt.colorbar() cbar.set_label('Frequencies (1)') plt.grid() if type(thetalabs) != type('auto'): ax.set_thetagrids((angs+dang/2.)*180./np.pi, thetalabs) elif lpvals[0] == 'linepoint': if lkind == 'multicol': ltyp = gen.auto_val(lpvals[3],'-') lmrk = gen.auto_val(lpvals[4],'x') colbar = gen.auto_val(lpvals[5],'spectral_r') Nang = gen.auto_val(lpvals[6],8) # Setting up colors for each label # From: http://stackoverflow.com/questions/15235630/matplotlib-pick-up-one-color-associated-to-one-value-in-a-colorbar vcolmin = np.min(ev) vcolmax = np.max(ev) my_cmap = plt.cm.get_cmap(colbar) norm = mpl.colors.Normalize(vcolmin, vcolmax) for ie in range(dime-1): labcol = my_cmap(norm(ev[ie])) plt.plot([ang[ie], ang[ie+1]], [speed[ie], speed[ie+1]], ltyp, marker=lmrk, color=labcol) ie = dime-1 labcol = my_cmap(norm(ev[ie])) lcolS = gen.coldec_hex(labcol[0:3]) plt.plot(ang[ie], speed[ie], ltyp, marker=lmrk, color=lcolS) # FROM: http://stackoverflow.com/questions/8342549/matplotlib-add-colorbar-to-a-sequence-of-line-plots # For matplotlib v1.3 or greater the code becomes: sm = plt.cm.ScalarMappable(cmap=colbar, norm=norm) # fake up the array of the scalar mappable. Urgh... sm._A = [] cbar = plt.colorbar(sm) cbar.set_label(lpvals[2] + ' (' + units_lunits(eunit) + ')') elif lkind == 'multicoltime': ltyp = gen.auto_val(lpvals[3],'-') lmrk = gen.auto_val(lpvals[4],'x') colbar = gen.auto_val(lpvals[5],'spectral_r') Nang = gen.auto_val(lpvals[6],8) timekind = lpvals[7] timefmt = lpvals[8] timelabel = lpvals[9].replace('!',' ') # Setting up colors for each label # From: http://stackoverflow.com/questions/15235630/matplotlib-pick-up-one-color-associated-to-one-value-in-a-colorbar vcolmin = np.min(ev) vcolmax = np.max(ev) my_cmap = plt.cm.get_cmap(colbar) norm = mpl.colors.Normalize(vcolmin, vcolmax) for ie in range(dime-1): labcol = my_cmap(norm(ev[ie])) lcolS = gen.coldec_hex(labcol[0:3]) plt.plot([ang[ie], ang[ie+1]], [speed[ie], speed[ie+1]], ltyp, marker=lmrk, color=lcolS) ie = dime-1 labcol = my_cmap(norm(ev[ie])) lcolS = gen.coldec_hex(labcol[0:3]) plt.plot(ang[ie], speed[ie], ltyp, marker=lmrk, color=lcolS) # FROM: http://stackoverflow.com/questions/8342549/matplotlib-add-colorbar-to-a-sequence-of-line-plots # For matplotlib v1.3 or greater the code becomes: sm = plt.cm.ScalarMappable(cmap=colbar, norm=norm) # fake up the array of the scalar mappable. Urgh... sm._A = [] cbar = plt.colorbar(sm, ticks=timepos) cbar.set_label(timelabel) cbar.ax.set_yticklabels(timelabels) # An attempt using text... #maxt = np.max(timepos) #for it in range(len(timelabels)): # daxistT = 0.6 # iaxistT = (1. - daxistT)/2. # itt = (timepos[it]-timepos[0])*daxistT/(maxt-timepos[0]) # labcol = my_cmap(norm(timepos[it])) # plt.annotate(timelabels[it], xy=(0.87,iaxistT+itt), color=labcol, \ # xycoords='figure fraction', multialignment='center') #plt.annotate(timelabel, xy=(0.97,0.5), color='k', rotation=90, \ # rotation_mode="anchor", xycoords='figure fraction', horizontalalignment='center') elif lkind == 'singlecol': ltyp = gen.auto_val(lpvals[2],'-') lmrk = gen.auto_val(lpvals[3],'x') lcol = gen.auto_val(lpvals[4],'b') Nang = gen.auto_val(lpvals[5],8) plt.plot(ang, speed, ltyp, marker=lmrk, color=lcol) elif lpvals[0] == 'scatter': if lkind == 'multicol': lmrk = gen.auto_val(lpvals[3],'x') colbar = gen.auto_val(lpvals[4],'spectral_r') Nang = gen.auto_val(lpvals[5],8) plt.scatter(ang, speed, c=ev, cmap=colbar, marker=lmrk) cbar = plt.colorbar() cbar.set_label(lpvals[2] + ' (' + units_lunits(eunit) + ')') elif lkind == 'multicoltime': lmrk = gen.auto_val(lpvals[3],'x') colbar = gen.auto_val(lpvals[4],'spectral_r') Nang = gen.auto_val(lpvals[5],8) timekind = lpvals[6] timefmt = lpvals[7] timelabel = lpvals[8].replace('!',' ') plt.scatter(ang, speed, c=ev, cmap=colbar, marker=lmrk) cbar = plt.colorbar(ticks=timepos) cbar.set_label(timelabel) cbar.ax.set_yticklabels(timelabels) elif lkind == 'singlecol': lmrk = gen.auto_val(lpvals[2],'x') lcol = gen.auto_val(lpvals[3],'b') Nang = gen.auto_val(lpvals[4],8) plt.plot(ang, speed, ',', marker=lmrk, color=lcol) if thetalabs == 'cardinals': if Nang == 4: thetalabs = ['N', 'E', 'S', 'W'] elif Nang == 8: thetalabs = ['N', 'NE', 'E', 'SE', 'S', 'SW', 'W', 'NW'] elif Nang == 16: thetalabs= ['N', 'NNE', 'NE', 'ENE', 'E', 'ESE', 'SE', 'SSE', 'S', 'SSW',\ 'SW', 'WSW', 'W', 'WNW', 'NW', 'NNW'] else: print errormsg print ' ' + fname + ': number of angles:', Nang, "not ready for '" + \ thetalabs + "' !!" print ' available ones: 4, 8, 16' quit(-1) dang = 2.*np.pi / (Nang) angs = np.arange(Nang,dtype=np.float)*dang - dang/2. ax.set_thetagrids((angs+dang/2.)*180./np.pi, thetalabs) ax.set_theta_zero_location('N') ax.set_theta_direction(-1) plt.annotate('wind (' + units_lunits(windu) + ')', xy=(0.75,0.06), color='k', \ xycoords='figure fraction', horizontalalignment='center') plt.title(gen.latex_text(titimg)) output_kind(kfig, figname, close) # Creation of the output file if lpvals[0] == 'anglespeedfreq' and outputfile: print ' ' + fname + ': Writting netCDF of frequencies of wind angle and ' + \ 'speeds...' newnc = NetCDFFile(figname + '.nc', 'w') # Dimension creation newdim = newnc.createDimension('angle', Nang) newdim = newnc.createDimension('speed', Nspeed) newdim = newnc.createDimension('bounds', 2) # Dimension variable newvar = newnc.createVariable('angle', 'f8', ('angle')) ncvar.basicvardef(newvar, 'angle', 'angle from which wind blows', 'degree') newvar[:] = angs newvar.setncattr('cell_method','angle_bounds') newvar = newnc.createVariable('angle_bounds', 'f8', ('angle','bounds')) ncvar.basicvardef(newvar,'angle_bounds', 'bounds of the angle sections', \ 'degree') for iang in range(Nang): # initial/ending of the angle section iasec = iang*dang - dang/2. if iasec < 0.: iasec = 2.*np.pi + iasec easec = iasec + dang newvar[iang,0] = iasec*180./np.pi newvar[iang,1] = easec*180./np.pi newnc.sync() newvar = newnc.createVariable('speed', 'f8', ('speed')) ncvar.basicvardef(newvar, 'speed', 'speed of wind', windu) newvar[:] = spds newvar.setncattr('cell_method','speed_bounds') newvar = newnc.createVariable('speed_bounds', 'f8', ('speed', 'bounds')) ncvar.basicvardef(newvar,'speed_bounds','bounds of the speed sections',windu) for ispd in range(Nspeed): # initial/ending of the speed section issec = ispd*dspeed - dspeed/2. if issec < 0.: issec = 0. essec = issec + dspeed newvar[ispd,0] = issec newvar[ispd,1] = essec newnc.sync() # Variables newvar = newnc.createVariable('frequency', 'f4', ('speed', 'angle'), \ fill_value=gen.fillValueF) ncvar.basicvardef(newvar, 'frequency', 'frequency of angle and speed', '1') newvar[:] = freqs[:] newnc.sync() # Global values ncvar.add_global_PyNCplot(newnc, 'drawing_tools.py', fname, '1.0') newnc.setncattr('original_file', origfilen) newnc.sync() newnc.close() print "Successful creation of file with frequencies '" + figname + ".nc' !!" return def plot_Taylor(stdv, corrv, corrpv, vunits, mtyp, mcol, msize, mlabs, labkind, \ tkind, itit, kfig, closefig): """ Function to draw a Taylor diagram (Taylor 2001) From script: # Copyright: This document has been placed in the public domain. Taylor diagram (Taylor, 2001) test implementation. https://gist.github.com/ycopin/3342888 __version__ = "Time-stamp: <2012-02-17 20:59:35 ycopin>" __author__ = "Yannick Copin " stdv= standard deviation values corrv= correlation values corrpv= pearson correlation p-value vunits= units of the variable mtyp= list of type of markers mcol= list of color of markers msize= list of size of markers mlabs= list of labels for markers (None for any) labkind= kind of labels in plot 'markfollow': on top of the mark of each pair of stddev, corr 'legend',[loc],[charsize]: as a traditional legend tkind: kind of Taylor plot 'direct': direct values 'norm': normalized to the stdandard deviation of reference itit= title of figure kfig= kind of figure closefig= whether figure has to be closed or not """ from matplotlib.projections import PolarAxes import mpl_toolkits.axisartist.floating_axes as FA import mpl_toolkits.axisartist.grid_finder as GF fname = 'plot_Taylor' colelines = '#DDDDDD' # Which size of the Taylor plot (should go until pi, since there are corr > 0.?) if np.min(corrv) < 0.: print warnmsg print ' ' + fname + ': minimum correlation:', np.min(corrv),'is negative !!' print ' extending Taylor plot until pi' maxang = np.pi else: maxang = np.pi/2. # Transforming correlations to given angles Tcorrv = np.arccos(corrv) plt.rc('text', usetex=True) Nvalues = len(stdv) colors, lines, points, Llines, Spoints = ColorsLinesPointsStyles(Nvalues, \ mcol, [','], mtyp, [2], msize, None) fig = plt.figure() rect = 111 tr = PolarAxes.PolarTransform() # Correlation labels if maxang <= np.pi/2.: rlocs = np.concatenate((np.arange(10)/10.,[0.95,0.99])) else: rlocs = np.concatenate(([-0.99, -0.95], (-10+np.arange(10))/10., [0.0], \ np.arange(10)/10., [0.95,0.99], [1.])) tlocs = np.arccos(rlocs) # Conversion to polar angles gl1 = GF.FixedLocator(tlocs) # Positions tf1 = GF.DictFormatter(dict(zip(tlocs, map(str,rlocs)))) # Standard deviation radius smin = 0 smax = np.max([1.25*stdv[0], np.max(stdv)]) label = '_' ghelper = FA.GridHelperCurveLinear(tr, extremes=(0,maxang,smin, smax), \ grid_locator1=gl1, tick_formatter1=tf1) ax = FA.FloatingSubplot(fig, rect, grid_helper=ghelper) fig.add_subplot(ax) # Adjust axes ax.axis["top"].set_axis_direction("bottom") # "Angle axis" ax.axis["top"].toggle(ticklabels=True, label=True) ax.axis["top"].major_ticklabels.set_axis_direction("top") ax.axis["top"].label.set_axis_direction("top") ax.axis["top"].label.set_text("Correlation") ax.axis["left"].set_axis_direction("bottom") # "X axis" ax.axis["left"].label.set_text("Standard deviation") if maxang <= np.pi/2.: ax.axis["right"].set_axis_direction("top") # "Y axis" ax.axis["right"].toggle(ticklabels=True) ax.axis["right"].major_ticklabels.set_axis_direction("left") else: ax.axis["right"].set_axis_direction("top") # "Y axis" ax.axis["right"].toggle(ticklabels=True) ax.axis["right"].major_ticklabels.set_axis_direction("bottom") ax.axis["bottom"].set_visible(False) # Useless # Contours along standard deviations ax.grid(False) ax = ax.get_aux_axes(tr) # Polar coordinates # Adding correlation lines if maxang > np.pi/2.: #thetalabs = ['1.', '0.99', '0.95', '0.9', '0.8', '0.7', '0.6', '0.5', '0.4', \ # '0.3', '0.2', '0.1', '0.0', -0.1, -0.2, -0.3, -0.4, -0.5, -0.6, -0.7, -0.8,\ # -0.9, -0.95, -0.99, -1.] thetalabs = ['0.99', '0.95', '0.8', '0.6', '0.4', '0.2', 0.0, -0.2, -0.4, \ -0.6, -0.8, -0.95, -0.99, -1.] else: thetalabs = ['0.99', '0.95', '0.8', '0.6', '0.4', '0.2'] # Correlation lines Nlref = 100 dang = maxang/(Nlref-1) lref = np.zeros((Nlref,2), dtype=np.float) for iang in thetalabs: ang = np.arccos(np.float(iang)) lref[:,0] = ang for ia in range(Nlref): lref[ia,1] = smax*ia/(Nlref-1) ax.plot(lref[:,0], lref[:,1], '--', color=colelines, linewidth=1) # Adding dash line from ref for ia in range(Nlref): lref[ia,0] = dang*ia lref[ia,1] = stdv[0] ax.plot(lref[:,0], lref[:,1], '-.', label='_', color='#AAAAAA', linewidth=1) # Adding concentrical circular lines from ref dang = np.pi/(Nlref-1) if maxang > np.pi/2.: Nlines = 8 rads = gen.pretty_int(0., stdv[0]*5./2.,Nlines) anglab = np.pi*7./8. else: Nlines = 4 rads = gen.pretty_int(0., stdv[0]*3./2.,Nlines) anglab = np.pi*1.4/2. for rad in rads: for ia in range(Nlref): x = stdv[0] + rad*np.cos(dang*ia) y = rad*np.sin(dang*ia) if np.sqrt(x**2+y**2) <= smax: lref[ia,0] = np.arctan2(y,x) lref[ia,1] = np.sqrt(x**2+y**2) else: lref[ia,0] = None lref[ia,1] = None # Labelling distance from ref if dang*ia >= anglab and dang*ia <= anglab+dang: Slab = '{0:.2g}'.format(rad) ax.annotate(Slab, xy=(lref[ia,0],lref[ia,1]), color='#AAAAAA') ax.plot(lref[:,0], lref[:,1], '--', color='#AAAAAA', linewidth=0.5) if labkind[0:6] == 'legend': for iv in range(Nvalues): if Nvalues != len(mlabs): print errormsg print ' ' + fname + ': number of vaules:', Nvalues, 'and labels:', \ len(mlabs), 'do not coincide !!' print ' labels provided:', mlabs quit(-1) ax.plot(Tcorrv[iv], stdv[iv], lines[iv], color=colors[iv], \ marker=points[iv], markersize=Spoints[iv], \ label=gen.latex_text(mlabs[iv])) else: for iv in range(Nvalues): ax.plot(Tcorrv[iv], stdv[iv], lines[iv], color=colors[iv], \ marker=points[iv], markersize=Spoints[iv]) if labkind == 'markfollow': for iv in range(Nvalues): ax.annotate(gen.latex_text(mlabs[iv]), xy=(Tcorrv[iv],stdv[iv])) elif labkind[0:6] == 'legend': legvals = labkind.split(',') gloc, gsize = legend_values(legvals[1] + ':' + legvals[2], ':') ax.legend(loc=gloc, prop={'size':gsize}) fig.suptitle(gen.latex_text(itit)) if tkind == 'norm': labstd = 'standard deviation (norm.)' else: labstd = 'standard deviation (' + units_lunits(vunits) + ')' output_kind(kfig, 'Taylor', closefig) return def plot_2D_shadow_2contour(varsv, varcv1, varcv2, vnames, dimxv, dimyv, dimxu, \ dimyu, xaxv, yaxv, dimn, cbarv, ckind1, clabfmt1, ckind2, clabfmt2, vs, vc1, vc2, \ uts, vtit, kfig, reva, mapv, ifclose): """ Plotting 3 2D fields, 1 with shadow and two with contour lines varsv= 2D values to plot with shading varcv1= 2D values to plot with contours 1 varcv2= 2D values to plot with contours 2 vnames= variable names for the figure dim[x/y]v = values at the axes of x and y dim[x/y]u = units at the axes of x and y xaxv= list with the x-axis paramteres [style, format, number and orientation] yaxv= list with the y-axis paramteres [style, format, number and orientation] dimn= dimension names to plot cbarv= list with the parameters of the color bar [colorbar, cbarfmt, cbaror] colorbar= name of the color bar to use cbarfmt= format of the numbers in the colorbar cbaror= orientation of the colorbar ckind1/2= contour kind of contour 1 and 2 'cmap': as it gets from colorbar 'fixc,[colname]': fixed color [colname], all stright lines 'fixsigc,[colname]': fixed color [colname], >0 stright, <0 dashed line clabfmt1/2= format of the labels in the contour 1 and 2 plot (None, no labels) vs= minmum and maximum values to plot in shadow vc1= vector with the levels for the contour 1 vc2= vector with the levels for the contour 2 uts= units of the variable [u-shadow, u-contour1, u-contour2] vtit= title of the variable kfig= kind of figure (jpg, pdf, png) reva= * 'transpose': reverse the axes (x-->y, y-->x) * 'flip'@[x/y]: flip the axis x or y mapv= map characteristics: [proj],[res] see full documentation: http://matplotlib.org/basemap/ [proj]: projection * 'cyl', cilindric * 'lcc', lamvbert conformal [res]: resolution: * 'c', crude * 'l', low * 'i', intermediate * 'h', high * 'f', full ifclose= boolean value whether figure should be close (finish) or not """ fname = 'plot_2D_shadow_2contour' if type(varsv) == type('S') and varsv == 'h': print fname + '_____________________________________________________________' print plot_2D_shadow_2contour.__doc__ quit() if len(varsv.shape) != 2: print errormsg print ' ' + fname + ': wrong variable shadow rank:', varsv.shape, \ 'is has to be 2D!!' quit(-1) if len(varcv1.shape) != 2: print errormsg print ' ' + fname + ': wrong variable contour 1 rank:', varcv1.shape, \ 'is has to be 2D!!' quit(-1) if len(varcv2.shape) != 2: print errormsg print ' ' + fname + ': wrong variable contour 2 rank:', varcv2.shape, \ 'is has to be 2D!!' quit(-1) # Axis ticks # Usually axis > x must be the lon, thus... dimxv0 = dimxv.copy() dimyv0 = dimyv.copy() dxn = dimxv.min() dxx = dimxv.max() dyn = dimyv.min() dyx = dimyv.max() # sens of the original x-axis and y-axis xneg=False if len(dimxv0.shape) == 1: if dimxv0[0] > dimxv0[1]: xneg=True else: if dimxv0[0,0] > dimxv0[0,1]: xneg=True yneg=False if len(dimyv0.shape) == 1: if dimyv0[0] > dimyv0[1]: yneg=True else: if dimyv0[0,0] > dimyv0[1,0]: yneg=True if xaxv[0] == 'pretty': dimxt0 = np.array(gen.pretty_int(dxn,dxx,xaxv[2])) axxtype='data' elif xaxv[0] == 'Nfix': dimxt0 = np.arange(0.,1.,1./(xaxv[2]+1)) dimxv0 = np.arange(0.,1.,1./varsv.shape[1]) axxtype='fixpixel' elif xaxv[0] == 'Vfix': dxnvfix = int(dxn/xaxv[2]) dimxt0 = np.arange(dxnvfix*xaxv[2],dxx,xaxv[2]) axxtype='data' if yaxv[0] == 'pretty': dimyt0 = np.array(gen.pretty_int(dyn,dyx,yaxv[2])) axytype='data' elif yaxv[0] == 'Nfix': dimyt0 = np.arange(0.,1.,1./(yaxv[2]+1)) dimyv0 = np.arange(0.,1.,1./varsv.shape[0]) axytype='fixpixel' elif yaxv[0] == 'Vfix': dynvfix = int(dyn/yaxv[2]) dimyt0 = np.arange(dynvfix*xaxv[2],dyx,yaxv[2]) axytype='data' if xneg: dimxt0 = dimxt0[::-1] if yneg: dimyt0 = dimyt0[::-1] dimxl0 = [] if xaxv[0] != 'Nfix': for i in range(len(dimxt0)): dimxl0.append('{:{style}}'.format(dimxt0[i], style=xaxv[1])) else: for i in range(len(dimxt0)): xv=dxn+i*(dxx-dxn)/(1.*xaxv[2]) dimxl0.append('{:{style}}'.format(xv, style=xaxv[1])) dimyl0 = [] if yaxv[0] != 'Nfix': for i in range(len(dimyt0)): dimyl0.append('{:{style}}'.format(dimyt0[i], style=yaxv[1])) else: for i in range(len(dimyt0)): yv=dyn+i*(dyx-dyn)/(1.*yaxv[2]) dimyl0.append('{:{style}}'.format(yv, style=yaxv[1])) dimxT0 = variables_values(dimn[0])[0] + ' (' + units_lunits(dimxu) + ')' dimyT0 = variables_values(dimn[1])[0] + ' (' + units_lunits(dimyu) + ')' if reva is not None: varcv1, dimxv, dimyv, dimxt, dimyt, dimxl, dimyl, dimxT, dimyT = \ transform(varcv1, reva) varcv2, dimxv, dimyv, dimxt, dimyt, dimxl, dimyl, dimxT, dimyT = \ transform(varcv2, reva) varsv, dimxv, dimyv, dimxt, dimyt, dimxl, dimyl, dimxT, dimyT = \ transform(varsv, reva, dxv=dimxv0, dyv=dimyv0, dxt=dimxt0, dyt=dimyt0, \ dxl=dimxl0, dyl=dimyl0, dxtit=dimxT0, dytit=dimyT0, axxkind=axxtype, \ axykind=axytype) else: dimxv = dimxv0 dimyv = dimyv0 dimxt = dimxt0 dimyt = dimyt0 dimxl = dimxl0 dimyl = dimyl0 dimxT = dimxT0 dimyT = dimyT0 if not mapv is None: if len(dimxv[:].shape) == 3: lon0 = dimxv[0,] lat0 = dimyv[0,] elif len(dimxv[:].shape) == 2: lon0 = dimxv[:] lat0 = dimyv[:] elif len(dimxv[:].shape) == 1: lon00 = dimxv[:] lat00 = dimyv[:] lon0 = np.zeros( (len(lat00),len(lon00)), dtype=np.float ) lat0 = np.zeros( (len(lat00),len(lon00)), dtype=np.float ) for iy in range(len(lat00)): lon0[iy,:] = lon00 for ix in range(len(lon00)): lat0[:,ix] = lat00 map_proj=mapv.split(',')[0] map_res=mapv.split(',')[1] dx = lon0.shape[1] dy = lon0.shape[0] nlon = np.min(lon0) xlon = np.max(lon0) nlat = np.min(lat0) xlat = np.max(lat0) lon2 = lon0[dy/2,dx/2] lat2 = lat0[dy/2,dx/2] print 'lon2:', lon2, 'lat2:', lat2, 'SW pt:', nlon, ',', nlat, 'NE pt:', \ xlon, ',', xlat if map_proj == 'cyl': m = Basemap(projection=map_proj, llcrnrlon=nlon, llcrnrlat=nlat, \ urcrnrlon=xlon, urcrnrlat= xlat, resolution=map_res) elif map_proj == 'lcc': m = Basemap(projection=map_proj, lat_0=lat2, lon_0=lon2, llcrnrlon=nlon, \ llcrnrlat=nlat, urcrnrlon=xlon, urcrnrlat= xlat, resolution=map_res) if len(dimxv.shape) == 1: lons, lats = np.meshgrid(dimxv, dimyv) else: if len(dimxv.shape) == 3: lons = dimxv[0,:,:] lats = dimyv[0,:,:] else: lons = dimxv[:] lats = dimyv[:] x,y = m(lons,lats) else: x,y = gen.lonlat2D(dimxv,dimyv) plt.rc('text', usetex=True) plt.pcolormesh(x, y, varsv, cmap=plt.get_cmap(cbarv[0]), vmin=vs[0], vmax=vs[1]) if cbarv[2] == 'horizontal': cbar = plt.colorbar(format=cbarv[1],orientation=cbarv[2]) # From: http://stackoverflow.com/questions/32050030/rotation-of-colorbar-tick-labels-in-matplotlib ticklabels= cbar.ax.get_xticklabels() Nticks = len(ticklabels) ticklabs = [] for itick in range(Nticks): ticklabs.append(ticklabels[itick].get_text()) cbar.ax.set_xticklabels(ticklabs,rotation=90) else: cbar = plt.colorbar(format=cbarv[1],orientation=cbarv[2]) # contours ## contkind1 = ckind1.split(',')[0] if contkind1 == 'cmap': cplot1 = plt.contour(x, y, varcv1, levels=vc1) elif contkind1 == 'fixc': plt.rcParams['contour.negative_linestyle'] = 'solid' coln1 = ckind1.split(',')[1] cplot1 = plt.contour(x, y, varcv1, levels=vc1, colors=coln1) elif contkind1 == 'fixsigc': coln1 = ckind1.split(',')[1] cplot1 = plt.contour(x, y, varcv1, levels=vc1, colors=coln1) else: print errormsg print ' ' + fname + ': contour kind 1 "' + contkind1 + '" not defined !!' quit(-1) if clabfmt1 is not None: plt.clabel(cplot1, fmt=clabfmt1) mincntS1 = format(vc1[0], clabfmt1[1:len(clabfmt1)]) maxcntS1 = format(vc1[len(vc1)-1], clabfmt1[1:len(clabfmt1)]) else: mincntS1 = '{:g}'.format(vc1[0]) maxcntS1 = '{:g}'.format(vc1[len(vc1)-1]) contkind2 = ckind2.split(',')[0] if contkind2 == 'cmap': cplot2 = plt.contour(x, y, varcv2, levels=vc2) elif contkind2 == 'fixc': plt.rcParams['contour.negative_linestyle'] = 'solid' coln2 = ckind2.split(',')[1] cplot2 = plt.contour(x, y, varcv2, levels=vc2, colors=coln2) elif contkind2 == 'fixsigc': coln2 = ckind2.split(',')[1] cplot2 = plt.contour(x, y, varcv2, levels=vc2, colors=coln2) else: print errormsg print ' ' + fname + ': contour kind 2 "' + contkind2 + '" not defined !!' quit(-1) if clabfmt2 is not None: plt.clabel(cplot2, fmt=clabfmt2) mincntS2 = format(vc2[0], clabfmt2[1:len(clabfmt2)]) maxcntS2 = format(vc2[len(vc2)-1], clabfmt2[1:len(clabfmt2)]) else: mincntS2 = '{:g}'.format(vc2[0]) maxcntS2 = '{:g}'.format(vc2[len(vc2)-1]) if not mapv is None: m.drawcoastlines() meridians = gen.pretty_int(nlon,xlon,xaxv[2]) m.drawmeridians(meridians,labels=[True,False,False,True]) parallels = gen.pretty_int(nlat,xlat,yaxv[2]) m.drawparallels(parallels,labels=[False,True,True,False]) plt.xlabel('W-E') plt.ylabel('S-N') else: plt.xlabel(dimxT) plt.ylabel(dimyT) plt.xticks(dimxt, dimxl, rotation=xaxv[3]) plt.yticks(dimyt, dimyl, rotation=yaxv[3]) #set the limits of the plot to the limits of the data plt.axis([x[0,0], x[0,x.shape[1]-1], y[0,0], y[y.shape[0]-1,0]]) # units labels cbar.set_label(gen.latex_text(vnames[0]) + ' (' + units_lunits(uts[0]) + ')') plt.annotate(gen.latex_text(vnames[1]) +' (' + units_lunits(uts[1]) + ') [' + \ mincntS1 + ', ' + maxcntS1 + ']', xy=(0.05,0.04), xycoords='figure fraction', \ color=coln1) plt.annotate(gen.latex_text(vnames[2]) +' (' + units_lunits(uts[2]) + ') [' + \ mincntS2 + ', ' + maxcntS2 + ']', xy=(0.55,0.04), xycoords='figure fraction', \ color=coln2) figname = '2Dfields_shadow-2contour' graphtit = gen.latex_text(vtit) plt.title(graphtit) output_kind(kfig, figname, ifclose) return def plot_bars(xvalues, yvalues, xaxv, yaxv, dimxu, dimyu, valaxis, xlabel, ylabel, \ labels, cols, width, gtit, lloc, lsiz, kfig, figname, ifclose): """ Function to plot a bar plot with multiple columns xvalues= list with the values along the x-ais yvalues= list with the values along the y-ais [x/y]axv= values at the axes of x and y dim[x/y]u= units at the axes of x and y valaxis= which axis holds the values 'x' or 'y' xlabel= label at the x-axis ylabel= label at the y-axis labels= list of labels for legend (None for no legend) cols= list of colors for the bars (single value for the same, 'auto' for automatic) width= size of the column gtit= title of the figure lloc= location of the legend (0, autmoatic) 1: 'upper right', 2: 'upper left', 3: 'lower left', 4: 'lower right', 5: 'right', 6: 'center left', 7: 'center right', 8: 'lower center', 9: 'upper center', 10: 'center' lsiz= font size of the legend kfig= kind of output: pdf, png, ps figname= name of the figure ifclose= whether figure should be closed """ fname = 'plot_bars' Nvalues = len(xvalues) # Maximum number of values: Lmaxvals = -10 xticks = xvalues[0] for iv in range(Nvalues): if len(xvalues[iv]) > Lmaxvals: Lmaxvals = len(xvalues[iv]) NOTcoinc = list(set(xvalues[iv]).difference(set(xticks))) if len(NOTcoinc) != 0: xticks = xticks + NOTcoinc xticks.sort() dxn = np.min(xvalues) dxx = np.max(xvalues) dyn = np.min(yvalues) dyx = np.max(yvalues) axstyles = ['pretty', 'Nfix', 'Stringlist', 'Vfix'] if xaxv[0] == 'pretty': dimxt = np.array(gen.pretty_int(dxn,dxx,xaxv[2])) dimxl = np.array(dimxt, dtype=str) elif xaxv[0] == 'Nfix': dimxl = np.arange(0.,1.,1./(xaxv[2]+1)) dimxt = np.arange(0.,1.,1./varsv.shape[1]) elif xaxv[0] == 'Stringlist': if len(xaxv[2]) != len(xticks): print warnmsg print ' ' + fname + ': number of ticks to plot=', len(xticks), \ 'and number of labels provided', len(xaxv[2]), 'differ !!' print ' ' + fname + ': ticks to plot=', xticks, 'and provided labels', \ xaxv[2], 'differ !!' dimxl = xaxv[2] dimxt = xticks elif xaxv[0] == 'Vfix': dxnvfix = int(dxn/xaxv[2]) dimxt = np.arange(dxnvfix*xaxv[2],dxx,xaxv[2]) else: print errormsg print ' ' + fname + ": x-xais style '" + xaxv[0] + "' not ready !!" print ' available ones: ', axstyles quit(-1) if yaxv[0] == 'pretty': dimyt = np.array(gen.pretty_int(dyn,dyx,yaxv[2])) dimyl = np.array(dimyt, dtype=str) elif yaxv[0] == 'Nfix': dimyt = np.arange(0.,1.,1./(yaxv[2]+1)) dimyl = np.arange(0.,1.,1./varsv.shape[0]) axytype='fixpixel' elif yaxv[0] == 'Vfix': dynvfix = int(dyn/yaxv[2]) dimyt = np.arange(dynvfix*xaxv[2],dyx,yaxv[2]) axytype='data' else: print errormsg print ' ' + fname + ": x-xais style '" + xaxv[0] + "' not ready !!" print ' available ones: ', axstyles quit(-1) if valaxis == 'x': orient = 'horizontal' else: orient = 'vertical' colvs = [] if len(cols) == 1: if cols[0] == 'auto': colvs = colorsauto[0:Nvalues+1] else: for ic in range(Nvalues): colvs.append(cols[0]) else: colvs = cols for iv in range(Nvalues): xvls = xvalues[iv] Lvalues = len(xvls) dxmean = np.mean(np.array(xvls[1:Lvalues])-np.array(xvls[0:Lvalues-1])) if dxmean < width*Nvalues: print warnmsg print ' ' + fname + ': mean distance among x-values:', dxmean, \ 'is smaller than the total number of bars with the given witdh (', \ width, '):', width*Nvalues print ' reduce widht of the column, should not be larger than:', \ dxmean/Nvalues if width*Nvalues < 0.01*dxmean: print warnmsg print ' ' + fname + ': mean distance among x-values:', dxmean, \ 'is 100-times larger than the total number of bars with the given ' + \ 'witdh (', width, '):', width*Nvalues print ' increase widht of the column, should not be smaller than:', \ 0.01*dxmean # Relative position of the column respect the xtick if np.mod(Nvalues,2) == 0: xrel = width*(iv - Nvalues/2.) else: xrel = width*(iv - (Nvalues-1)/2.) xrels = xrel*np.ones((Lvalues),dtype=np.float) if valaxis == 'x': if labels is not None and labels[iv] != 'None': plt.barh(xvls+xrels, yvalues[iv], height=width, color=colvs[iv], \ label=gen.latex_text(labels[iv])) else: plt.barh(xvls+xrels, yvalues[iv], height=width, color=colvs[iv]) else: if labels is not None and labels[iv] != 'None': plt.bar(xvls+xrels, yvalues[iv], width=width, color=colvs[iv], \ label=gen.latex_text(labels[iv])) else: plt.bar(xvls+xrels, yvalues[iv], width=width, color=colvs[iv]) if valaxis == 'x': plt.xticks(dimyt, dimyl, rotation=yaxv[3]) plt.yticks(dimxt, dimxl, rotation=xaxv[3]) plt.xlabel(gen.latex_text(ylabel) + ' (' + units_lunits(dimyu) + ')') if dimxu is not None: plt.ylabel(gen.latex_text(xlabel) + ' (' + units_lunits(dimxu) + ')') else: plt.ylabel(gen.latex_text(xlabel)) else: plt.xticks(dimxt, list(dimxl), rotation=xaxv[3]) plt.yticks(dimyt, list(dimyl), rotation=yaxv[3]) if dimxu is not None: plt.xlabel(gen.latex_text(xlabel) + ' (' + units_lunits(dimxu) + ')') else: plt.xlabel(gen.latex_text(xlabel)) plt.ylabel(gen.latex_text(ylabel) + ' (' + units_lunits(dimyu) + ')') if labels is not None: plt.legend(loc=lloc, prop={'size':lsiz}) plt.title(gen.latex_text(gtit)) output_kind(kfig, figname, ifclose) return def plot_bars_time(xvalues, yvalues, tpos, tlabs, yaxv, dimyu, valaxis, valrange, xlabel, \ ylabel, labels, cols, width, gtit, lloc, lsiz, kfig, figname, ifclose): """ Function to plot a bar plot with multiple columns xvalues= list with the values along the x-ais yvalues= list with the values along the y-ais tpos= position of the time-ticks tlabs= labels of the time-ticks yaxv= values at the axis y dimyu= units at the axis y valaxis= which axis holds the values 'x' or 'y' valrange= range of the axis with values xlabel= label at the x-axis ylabel= label at the y-axis labels= list of labels for legend (None for no legend) cols= list of colors for the bars (single value for the same, 'auto' for automatic) width= size of the column gtit= title of the figure lloc= location of the legend (0, autmoatic) 1: 'upper right', 2: 'upper left', 3: 'lower left', 4: 'lower right', 5: 'right', 6: 'center left', 7: 'center right', 8: 'lower center', 9: 'upper center', 10: 'center' lsiz= font size of the legend kfig= kind of output: pdf, png, ps figname= name of the figure ifclose= whether figure should be closed """ fname = 'plot_bars' Nvalues = len(xvalues) dyn = valrange[0] dyx = valrange[1] axstyles = ['pretty', 'Nfix', 'Stringlist', 'Vfix'] if yaxv[0] == 'pretty': dimyt = np.array(gen.pretty_int(dyn,dyx,yaxv[2])) dimyl = np.array(dimyt, dtype=str) elif yaxv[0] == 'Nfix': dimyt = np.arange(0.,1.,1./(yaxv[2]+1)) dimyl = np.arange(0.,1.,1./varsv.shape[0]) axytype='fixpixel' elif yaxv[0] == 'Vfix': dynvfix = int(dyn/yaxv[2]) dimyt = np.arange(dynvfix*xaxv[2],dyx,yaxv[2]) axytype='data' else: print errormsg print ' ' + fname + ": x-xais style '" + xaxv[0] + "' not ready !!" print ' available ones: ', axstyles quit(-1) colvs = [] if len(cols) == 1: if cols[0] == 'auto': colvs = colorsauto[0:Nvalues+1] else: for ic in range(Nvalues): colvs.append(cols[0]) else: colvs = cols # Adding grid #plt.rc('axes', axisbelow=True) #plt.grid() for iv in range(Nvalues): xvls = xvalues[iv] Lvalues = len(xvls) dxmean = np.mean(np.array(xvls[1:Lvalues])-np.array(xvls[0:Lvalues-1])) if dxmean < width*Nvalues: print warnmsg print ' ' + fname + ': mean distance among x-values:', dxmean, \ 'is smaller than the total number of bars with the given witdh (', \ width, '):', width*Nvalues print ' reduce widht of the column, should not be larger than:', \ dxmean/Nvalues if width*Nvalues < 0.1*dxmean: print warnmsg print ' ' + fname + ': mean distance among x-values:', dxmean, \ 'is 100-times larger than the total number of bars with the given ' + \ 'witdh (', width, '):', width*Nvalues print ' increase widht of the column, should not be smaller than:', \ 0.1*dxmean # Relative position of the column respect the xtick if np.mod(Nvalues,2) == 0: xrel = width*(iv - Nvalues/2.) else: xrel = width*(iv - (Nvalues-1)/2.) xrels = xrel*np.ones((Lvalues),dtype=np.float) if valaxis == 'x': if labels is not None and labels[iv] != 'None': plt.barh(xvls+xrels, yvalues[iv], height=width, color=colvs[iv], \ label=gen.latex_text(labels[iv])) else: plt.barh(xvls+xrels, yvalues[iv], height=width, color=colvs[iv]) else: if labels is not None and labels[iv] != 'None': plt.bar(xvls+xrels, yvalues[iv], width=width, color=colvs[iv], \ label=gen.latex_text(labels[iv])) else: plt.bar(xvls+xrels, yvalues[iv], width=width, color=colvs[iv]) if valaxis == 'x': plt.xticks(dimyt, dimyl, rotation=yaxv[3]) plt.yticks(tpos, tlabs, rotation=0) plt.xlabel(gen.latex_text(ylabel) + ' (' + units_lunits(dimyu) + ')') plt.ylabel(gen.latex_text(xlabel)) plt.xlim(dyn, dyx) else: plt.xticks(tpos, tlabs) plt.yticks(dimyt, list(dimyl), rotation=yaxv[3]) plt.xlabel(gen.latex_text(xlabel)) plt.ylabel(gen.latex_text(ylabel) + ' (' + units_lunits(dimyu) + ')') plt.ylim(dyn, dyx) if labels is not None: plt.legend(loc=lloc, prop={'size':lsiz}) plt.title(gen.latex_text(gtit)) output_kind(kfig, figname, ifclose) return def plot_bars_line(bxvalues, byvalues, lxvalues, lyvalues, xaxv, yaxv, dimxu, dimyu, \ valaxis, valrange, xlabel, ylabel, blabels, llabels, bcols, width, coll, typl, ptl,\ wdtl, ptz, ptf, gtit, lloc, lsiz, kfig, figname, ifclose): """ Function to plot a bar and lines plot with multiple columns bxvalues= list with the values along the x-ais for bar plot byvalues= list with the values along the y-ais for bar plot lxvalues= list with the values along the x-ais for lines plot lyvalues= list with the values along the y-ais for lines plot [x/y]axv= values at the axes of x and y dim[x/y]u= units at the axes of x and y valaxis= which axis holds the values 'x' or 'y' valrange= range of values along the values axis xlabel= label at the x-axis ylabel= label at the y-axis blabels= list of labels for legend (None for no legend) for bars llabels= list of labels for legend (None for no legend) for lines bcols= list of colors for the bars (single value for the same, 'auto' for automatic) width= size of the column coll= ',' list of colors for the lines, 'None' for automatic, single value all the same typl= ',' list of type for the lines, 'None' for automatic, single value all the same ptl= ',' list of type of points for the lines, 'None' for automatic, single value all the same wdtl= ',' list of width for the lines, 'None' for automatic, single value all the same ptz= ',' list of size of points for the lines, 'None' for automatic, single value all the same ptf= frequency of point plotting, 'all' for all time steps gtit= title of the figure lloc= location of the legend (0, autmoatic) 1: 'upper right', 2: 'upper left', 3: 'lower left', 4: 'lower right', 5: 'right', 6: 'center left', 7: 'center right', 8: 'lower center', 9: 'upper center', 10: 'center' lsiz= font size of the legend kfig= kind of output: pdf, png, ps figname= name of the figure ifclose= whether figure should be closed """ fname = 'plot_bars_line' bNvalues = len(bxvalues) lNvalues = len(lxvalues) if lNvalues > 0: # Lines' characteristics cols, lins, pts, lws, pss = ColorsLinesPointsStyles(lNvalues, coll, typl, \ ptl, wdtl, ptz, ptf) # Maximum number of values: Lmaxvals = -10 if bNvalues > 0: xticks = bxvalues[0] for iv in range(bNvalues): if len(bxvalues[iv]) > Lmaxvals: Lmaxvals = len(bxvalues[iv]) NOTcoinc = list(set(bxvalues[iv]).difference(set(xticks))) if len(NOTcoinc) != 0: xticks = xticks + NOTcoinc xticks.sort() if lNvalues > 0: if bNvalues == 0: xticks = lxvalues[0] for iv in range(lNvalues): if len(lxvalues[iv]) > Lmaxvals: Lmaxvals = len(lxvalues[iv]) NOTcoinc = list(set(lxvalues[iv]).difference(set(xticks))) if len(NOTcoinc) != 0: xticks = xticks + NOTcoinc xticks.sort() dxn = np.min([bxvalues, lxvalues]) dxx = np.max([bxvalues, lxvalues]) dyn = valrange[0] dyx = valrange[1] axstyles = ['pretty', 'Nfix', 'Stringlist', 'Vfix'] if xaxv[0] == 'pretty': dimxt = np.array(gen.pretty_int(dxn,dxx,xaxv[2])) dimxl = np.array(dimxt, dtype=str) elif xaxv[0] == 'Nfix': dimxl = np.arange(0.,1.,1./(xaxv[2]+1)) dimxt = np.arange(0.,1.,1./varsv.shape[1]) elif xaxv[0] == 'Stringlist': if len(xaxv[2]) != len(xticks): print warnmsg print ' ' + fname + ': number of ticks to plot=', len(xticks), \ 'and number of labels provided', len(xaxv[2]), 'differ !!' print ' ' + fname + ': ticks to plot=', xticks, 'and provided labels', \ xaxv[2], 'differ !!' dimxl = xaxv[2] dimxt = xticks elif xaxv[0] == 'Vfix': dxnvfix = int(dxn/xaxv[2]) dimxt = np.arange(dxnvfix*xaxv[2],dxx,xaxv[2]) else: print errormsg print ' ' + fname + ": x-xais style '" + xaxv[0] + "' not ready !!" print ' available ones: ', axstyles quit(-1) if yaxv[0] == 'pretty': dimyt = np.array(gen.pretty_int(dyn,dyx,yaxv[2])) dimyl = np.array(dimyt, dtype=str) elif yaxv[0] == 'Nfix': dimyt = np.arange(0.,1.,1./(yaxv[2]+1)) dimyl = np.arange(0.,1.,1./varsv.shape[0]) axytype='fixpixel' elif yaxv[0] == 'Vfix': dynvfix = int(dyn/yaxv[2]) dimyt = np.arange(dynvfix*xaxv[2],dyx,yaxv[2]) axytype='data' else: print errormsg print ' ' + fname + ": x-xais style '" + xaxv[0] + "' not ready !!" print ' available ones: ', axstyles quit(-1) if valaxis == 'x': orient = 'horizontal' else: orient = 'vertical' bcolvs = [] if len(bcols) == 1: if cols[0] == 'auto': bcolvs = colorsauto[0:bNvalues+1] else: for ic in range(bNvalues): bcolvs.append(bcols[0]) else: bcolvs = bcols if bNvalues > 0: for iv in range(bNvalues): xvls = bxvalues[iv] Lvalues = len(xvls) dxmean = np.mean(np.array(xvls[1:Lvalues])-np.array(xvls[0:Lvalues-1])) if dxmean < width*bNvalues: print warnmsg print ' ' + fname + ': mean distance among x-values:', dxmean, \ 'is smaller than the total number of bars with the given witdh (', \ width, '):', width*bNvalues print ' reduce widht of the column, should not be larger than:', \ dxmean/bNvalues if width*bNvalues < 0.01*dxmean: print warnmsg print ' ' + fname + ': mean distance among x-values:', dxmean, \ 'is 100-times larger than the total number of bars with the given'+\ ' witdh (', width, '):', width*bNvalues print ' increase widht of the column, should not be smaller ' + \ 'than:', 0.01*dxmean # Relative position of the column respect the xtick if np.mod(bNvalues,2) == 0: xrel = width*(iv - bNvalues/2.) else: xrel = width*(iv - (bNvalues-1)/2.) xrels = xrel*np.ones((Lvalues),dtype=np.float) if valaxis == 'x': if blabels is not None and blabels[iv] != 'None': plt.barh(xvls+xrels, byvalues[iv], height=width,color=bcolvs[iv],\ label=gen.latex_text(blabels[iv])) else: plt.barh(xvls+xrels, byvalues[iv], height=width, color=bcolvs[iv]) else: if blabels is not None and blabels[iv] != 'None': plt.bar(xvls+xrels, byvalues[iv], width=width, color=bcolvs[iv], \ label=gen.latex_text(blabels[iv])) else: plt.bar(xvls+xrels, byvalues[iv], width=width, color=bcolvs[iv]) if lNvalues > 0: for iv in range(lNvalues): if valaxis == 'x': if llabels is not None and llabels[iv] != 'None': plt.plot(lyvalues[iv], lxvalues[iv], lins[iv], marker=pts[iv], \ color=cols[iv], label=gen.latex_text(llabels[iv]), \ linewidth=lws[iv], markersize=pss[iv], markevery=ptf) else: plt.plot(lyvalues[iv], lxvalues[iv], lins[iv], marker=pts[iv], \ color=cols[iv],linewidth=lws[iv], markersize=pss[iv], \ markevery=ptf) else: if llabels is not None and llabels[iv] != 'None': plt.plot(lxvalues[iv], lyvalues[iv], lins[iv], marker=pts[iv], \ color=cols[iv], label=gen.latex_text(llabels[iv]), \ linewidth=lws[iv], markersize=pss[iv], markevery=ptf) else: plt.plot(lxvalues[iv], lyvalues[iv], lins[iv], marker=pts[iv], \ color=cols[iv],linewidth=lws[iv], markersize=pss[iv], \ markevery=ptf) if valaxis == 'x': plt.xticks(dimyt, dimyl, rotation=yaxv[3]) plt.yticks(dimxt, list(dimxl), rotation=xaxv[3]) plt.xlabel(gen.latex_text(ylabel) + ' (' + units_lunits(dimyu) + ')') if dimxu is not None: plt.ylabel(gen.latex_text(xlabel) + ' (' + units_lunits(dimxu) + ')') else: plt.ylabel(gen.latex_text(xlabel)) plt.xlim(dyn, dyx) else: plt.xticks(dimxt, list(dimxl), rotation=xaxv[3]) plt.yticks(dimyt, list(dimyl), rotation=yaxv[3]) if dimxu is not None: plt.xlabel(gen.latex_text(xlabel) + ' (' + units_lunits(dimxu) + ')') else: plt.xlabel(gen.latex_text(xlabel)) plt.ylabel(gen.latex_text(ylabel) + ' (' + units_lunits(dimyu) + ')') plt.ylim(dyn, dyx) if blabels is not None or llabels is not None: plt.legend(loc=lloc, prop={'size':lsiz}) plt.title(gen.latex_text(gtit)) output_kind(kfig, figname, ifclose) return def plot_bars_line_time(bxvalues, byvalues, lxvalues, lyvalues, tpos, tlabs, yaxv, dimyu, \ valaxis, valrange, xlabel, ylabel, blabels, llabels, bcols, width, coll, typl, ptl,\ wdtl, ptz, ptf, gtit, lloc, lsiz, kfig, figname, ifclose): """ Function to plot a bar and lines plot with multiple columns with a time-axis bxvalues= list with the values along the x-ais for bar plot byvalues= list with the values along the y-ais for bar plot lxvalues= list with the values along the x-ais for lines plot lyvalues= list with the values along the y-ais for lines plot tpos= position of the time-ticks tlabs= labels of the time-ticks yaxv= values at the axes of y dimyu= units at the axes of y valaxis= which axis holds the values 'x' or 'y' valrange= range of values along the values axis xlabel= label at the x-axis ylabel= label at the y-axis blabels= list of labels for legend (None for no legend) for bars llabels= list of labels for legend (None for no legend) for lines bcols= list of colors for the bars (single value for the same, 'auto' for automatic) width= size of the column coll= ',' list of colors for the lines, 'None' for automatic, single value all the same typl= ',' list of type for the lines, 'None' for automatic, single value all the same ptl= ',' list of type of points for the lines, 'None' for automatic, single value all the same wdtl= ',' list of width for the lines, 'None' for automatic, single value all the same ptz= ',' list of size of points for the lines, 'None' for automatic, single value all the same ptf= frequency of point plotting, 'all' for all time steps gtit= title of the figure lloc= location of the legend (0, autmoatic) 1: 'upper right', 2: 'upper left', 3: 'lower left', 4: 'lower right', 5: 'right', 6: 'center left', 7: 'center right', 8: 'lower center', 9: 'upper center', 10: 'center' lsiz= font size of the legend kfig= kind of output: pdf, png, ps figname= name of the figure ifclose= whether figure should be closed """ fname = 'plot_bars_line_time' bNvalues = len(bxvalues) lNvalues = len(lxvalues) if lNvalues > 0: # Lines' characteristics cols, lins, pts, lws, pss = ColorsLinesPointsStyles(lNvalues, coll, typl, \ ptl, wdtl, ptz, ptf) # Maximum number of values: Lmaxvals = -10 if bNvalues > 0: xticks = bxvalues[0] for iv in range(bNvalues): if len(bxvalues[iv]) > Lmaxvals: Lmaxvals = len(bxvalues[iv]) NOTcoinc = list(set(bxvalues[iv]).difference(set(xticks))) if len(NOTcoinc) != 0: xticks = xticks + NOTcoinc xticks.sort() if lNvalues > 0: if bNvalues == 0: xticks = lxvalues[0] for iv in range(lNvalues): if len(lxvalues[iv]) > Lmaxvals: Lmaxvals = len(lxvalues[iv]) NOTcoinc = list(set(lxvalues[iv]).difference(set(xticks))) if len(NOTcoinc) != 0: xticks = xticks + NOTcoinc xticks.sort() dxn = np.min([bxvalues, lxvalues]) dxx = np.max([bxvalues, lxvalues]) dyn = valrange[0] dyx = valrange[1] if yaxv[0] == 'pretty': dimyt = np.array(gen.pretty_int(dyn,dyx,yaxv[2])) dimyl = np.array(dimyt, dtype=str) elif yaxv[0] == 'Nfix': dimyt = np.arange(0.,1.,1./(yaxv[2]+1)) dimyl = np.arange(0.,1.,1./varsv.shape[0]) axytype='fixpixel' elif yaxv[0] == 'Vfix': dynvfix = int(dyn/yaxv[2]) dimyt = np.arange(dynvfix*xaxv[2],dyx,yaxv[2]) axytype='data' else: print errormsg print ' ' + fname + ": x-xais style '" + xaxv[0] + "' not ready !!" print ' available ones: ', axstyles quit(-1) if valaxis == 'x': orient = 'horizontal' else: orient = 'vertical' bcolvs = [] if len(bcols) == 1: if cols[0] == 'auto': bcolvs = colorsauto[0:bNvalues+1] else: for ic in range(bNvalues): bcolvs.append(bcols[0]) else: bcolvs = bcols if bNvalues > 0: for iv in range(bNvalues): xvls = bxvalues[iv] Lvalues = len(xvls) dxmean = np.mean(np.array(xvls[1:Lvalues])-np.array(xvls[0:Lvalues-1])) if dxmean < width*bNvalues: print warnmsg print ' ' + fname + ': mean distance among x-values:', dxmean, \ 'is smaller than the total number of bars with the given witdh (', \ width, '):', width*bNvalues print ' reduce widht of the column, should not be larger than:', \ dxmean/bNvalues if width*bNvalues < 0.01*dxmean: print warnmsg print ' ' + fname + ': mean distance among x-values:', dxmean, \ 'is 100-times larger than the total number of bars with the given'+\ ' witdh (', width, '):', width*bNvalues print ' increase widht of the column, should not be smaller ' + \ 'than:', 0.01*dxmean # Relative position of the column respect the xtick if np.mod(bNvalues,2) == 0: xrel = width*(iv - bNvalues/2.) else: xrel = width*(iv - (bNvalues-1)/2.) xrels = xrel*np.ones((Lvalues),dtype=np.float) if valaxis == 'x': if blabels is not None and blabels[iv] != 'None': plt.barh(xvls+xrels, byvalues[iv], height=width,color=bcolvs[iv],\ label=gen.latex_text(blabels[iv])) else: plt.barh(xvls+xrels, byvalues[iv], height=width, color=bcolvs[iv]) else: if blabels is not None and blabels[iv] != 'None': plt.bar(xvls+xrels, byvalues[iv], width=width, color=bcolvs[iv], \ label=gen.latex_text(blabels[iv])) else: plt.bar(xvls+xrels, byvalues[iv], width=width, color=bcolvs[iv]) if lNvalues > 0: for iv in range(lNvalues): if valaxis == 'x': if llabels is not None and llabels[iv] != 'None': plt.plot(lyvalues[iv], lxvalues[iv], lins[iv], marker=pts[iv], \ color=cols[iv], label=gen.latex_text(llabels[iv]), \ linewidth=lws[iv], markersize=pss[iv], markevery=ptf) else: plt.plot(lyvalues[iv], lxvalues[iv], lins[iv], marker=pts[iv], \ color=cols[iv],linewidth=lws[iv], markersize=pss[iv], \ markevery=ptf) else: if llabels is not None and llabels[iv] != 'None': plt.plot(lxvalues[iv], lyvalues[iv], lins[iv], marker=pts[iv], \ color=cols[iv], label=gen.latex_text(llabels[iv]), \ linewidth=lws[iv], markersize=pss[iv], markevery=ptf) else: plt.plot(lxvalues[iv], lyvalues[iv], lins[iv], marker=pts[iv], \ color=cols[iv],linewidth=lws[iv], markersize=pss[iv], \ markevery=ptf) if valaxis == 'x': plt.xticks(dimyt, dimyl, rotation=yaxv[3]) plt.yticks(tpos, tlabs, rotation=0) plt.xlabel(gen.latex_text(ylabel) + ' (' + units_lunits(dimyu) + ')') plt.ylabel(gen.latex_text(xlabel)) plt.xlim(dyn, dyx) else: plt.xticks(tpos, tlabs, rotation=0) plt.yticks(dimyt, list(dimyl), rotation=yaxv[3]) plt.xlabel(gen.latex_text(xlabel)) plt.ylabel(gen.latex_text(ylabel) + ' (' + units_lunits(dimyu) + ')') plt.ylim(dyn, dyx) if blabels is not None or llabels is not None: plt.legend(loc=lloc, prop={'size':lsiz}) plt.title(gen.latex_text(gtit)) output_kind(kfig, figname, ifclose) return def plot_time_lag(prevals, futvals, tvals, xaxv, yaxv, axistype, prelab, futlab, \ preu, futu, prerange, futrange, figtype, labels, tname, tpos, tlab, gtit, lloc, \ lsiz, kfig, figname, ifclose): """ Function to plot a time-lag figure (x, previous values; y, future values) prevals= list with the previous values futvals= list with future values tavals= list of time-values (common for couples) [x/y]axv= values at the axes x and y axistype: type of axis to be plotted 'centered': crossed at 0,0 at the center of the figure 'box': around the figure [pre/fut]lab= variable label at previous and future-axis [pre/fut]u= units of the previous and future variable-axis [pre/fut]range: ranges of the revious and future variable-axis figtype= [kindname],[valueskind] kind of time-lag plot 'repeatPeriod',[Nlag],[period],[colorbar],[cbarfmt],[cbaror],[ltype],[lwidth],[mtype],[msize]: time-lag for a given repeating sub-period, Line-conected points following a colorbar and time-values [Nlag]: number of time steps as lag [period]: period to be repeated allover the time-data [colorbar]: name of the color bar to use ('auto' for rainbow) [cbarfmt]: format of the numbers in the colorbar [cbaror]: orientation of the colorbar ('auto' for vertical) [ltype]: type of the lines (single value for the same, or 'auto') [lsize]: width of the lines (single value for the same, or 'auto') [mtype]: type of the markers (single value for the same, or 'auto') [msize]: size of the markers (single value for the same, or 'auto') 'shadTline',[Nlag],[colorbar],[cbarfmt],[cbaror],[ltype],[lwidth],[mtype],[msize]: Line-conected points following a colorbar and time-values [Nlag]: number of time steps as lag [colorbar]: name of the color bar to use ('auto' for rainbow) [cbarfmt]: format of the numbers in the colorbar [cbaror]: orientation of the colorbar ('auto' for vertical) [ltype]: type of the lines (single value for the same, or 'auto') [lsize]: width of the lines (single value for the same, or 'auto') [mtype]: type of the markers (single value for the same, or 'auto') [msize]: size of the markers (single value for the same, or 'auto') 'simplepts',[Nlag],[col],[type],[size]: Simple points assuming that values have all the same times [Nlag]: number of time steps as lag [col]: color of the points (single value for the same, or 'auto') [type]:type of the markers (single value for the same, or 'auto') [size]: size of the markers (single value for the same, or 'auto') labels= list of labels for legend (None for no legend, and 'None' for no specific label) tname= label of the time-axis tpos= position of the time-ticks tlab= labels of the time-ticks gtit= title of the figure lloc= location of the legend (0, autmoatic) 1: 'upper right', 2: 'upper left', 3: 'lower left', 4: 'lower right', 5: 'right', 6: 'center left', 7: 'center right', 8: 'lower center', 9: 'upper center', 10: 'center' lsiz= font size of the legend kfig= kind of output: pdf, png, ps figname= name of the figure ifclose= whether figure should be closed """ from scipy import stats as sts fname = 'plot_time_lag' Nvalues = len(prevals) dxn = prerange[0] dxx = prerange[1] dyn = futrange[0] dyx = futrange[1] axstyles = ['pretty', 'Nfix', 'Stringlist', 'Vfix'] if xaxv[0] == 'pretty': dimxt = np.array(gen.pretty_int(dxn,dxx,xaxv[2])) dimxl = np.array(dimxt, dtype=str) elif xaxv[0] == 'Nfix': dimxl = np.arange(dxn,dxx,(dxx-dxn)/(xaxv[2]+1)) dimxt = np.arange(dxn,dxx,(dxx-dxn)/Lxmaxvals) elif xaxv[0] == 'Stringlist': if len(xaxv[2]) != len(xticks): print warnmsg print ' ' + fname + ': number of ticks to plot=', len(xticks), \ 'and number of labels provided', len(xaxv[2]), 'differ !!' print ' ' + fname + ': ticks to plot=', xticks, 'and provided labels', \ xaxv[2], 'differ !!' dimxl = xaxv[2] dimxt = xticks elif xaxv[0] == 'Vfix': dxnvfix = int(dxn/xaxv[2]) dimxt = np.arange(dxnvfix*xaxv[2],dxx,xaxv[2]) else: print errormsg print ' ' + fname + ": x-xais style '" + xaxv[0] + "' not ready !!" print ' available ones: ', axstyles quit(-1) if yaxv[0] == 'pretty': dimyt = np.array(gen.pretty_int(dyn,dyx,yaxv[2])) dimyl = np.array(dimyt, dtype=str) elif yaxv[0] == 'Nfix': dimyt = np.arange(dyn,dyx,(dyx-dyn)/(yaxv[2]+1)) dimyl = np.arange(dyn,dyx,(dyx-dyn)/Lymaxvals) axytype='fixpixel' elif yaxv[0] == 'Vfix': dynvfix = int(dyn/yaxv[2]) dimyt = np.arange(dynvfix*xaxv[2],dyx,yaxv[2]) axytype='data' else: print errormsg print ' ' + fname + ": x-xais style '" + xaxv[0] + "' not ready !!" print ' available ones: ', axstyles quit(-1) # kind of time-lag figure: figv = figtype.split(',') figtypen = figv[0] plt.rc('text', usetex=True) fig, ax = plt.subplots(1) for iv in range(Nvalues): xvs = np.array(prevals[iv]) yvs = np.array(futvals[iv]) try: with gen.Capturing() as output: gen.same_shape(np.array(xvs), np.array(yvs)) except: print errormsg print ' ' + fname + ': shape of matrix from couple:', iv, 'differ !!' for sout in output: print sout quit(-1) dimt = xvs.shape[0] tvalues = tvals[iv] if figtypen == 'repeatPeriod': expectargs = "'repeatPeriod',[Nlag],[period],[colorbar],[cbarfmt]," + \ "[cbaror],[ltype],[lwidth],[mtype],[msize]" check_arguments(fname + " & 'repeatPeriod'",figtype,expectargs,',') Nlag = int(figv[1]) period = int(figv[2]) colbar = gen.auto_val(figv[3], 'rainbow') check_colorBar(colbar) cbarfmt = figv[4] cbaror = gen.auto_val(figv[5], 'vertical') ltype = gen.str_list_rep(figv[6],'@',Nvalues) lwidth = gen.str_list_rep(figv[7],'@',Nvalues) mtype = gen.str_list_rep(figv[8],'@',Nvalues) msize = gen.str_list_rep(figv[9],'@',Nvalues) my_cmap = plt.cm.get_cmap(colbar) Nperiods = dimt/period tminv = np.min(tvals[iv]) tmaxv = np.max(tvals[iv]) norm = mpl.colors.Normalize(0.,Nperiods) # Normalizing position of the ticks if iv == 0: tpos = tpos*Nperiods/tmaxv if labels is not None and labels[iv] != 'None': for ip in range(Nperiods): clv = my_cmap(norm(ip*1.)) for it in range(period+Nlag): Tt = period*ip+it if Tt + Nlag + 1 > dimt-1: break if ip == 0 and it == 0: plt.plot([xvs[Tt],xvs[Tt+1]], [yvs[Tt+Nlag],yvs[Tt+Nlag+1]], \ ltype[iv], color=clv, linewidth=np.float(lwidth[iv]), \ marker=mtype[iv], markersize=np.float(msize[iv]), \ label=gen.latex_text(labels[iv])) else: plt.plot([xvs[Tt],xvs[Tt+1]], [yvs[Tt+Nlag],yvs[Tt+Nlag+1]], \ ltype[iv], color=clv, linewidth=np.float(lwidth[iv]), \ marker=mtype[iv], markersize=np.float(msize[iv])) else: for ip in range(Nperiods): clv = my_cmap(norm(ip*1.)) for it in range(period+Nlag): Tt = period*ip+it if Tt + Nlag + 1 > dimt-1: break plt.plot([xvs[it], xvs[it+1]], [yvs[it+Nlag], yvs[it+Nlag+1]], \ ltype[iv], color=clv, linewidth=lwidth[iv], marker=mtype[iv], \ markersize=msize[iv]) elif figtypen == 'shadTline': expectargs = "'shadTline',[Nlag],[colorbar],[cbarfmt],[cbaror]," + \ "[ltype],[lwidth],[mtype],[msize]" check_arguments(fname + " & 'shadTline'",figtype,expectargs,',') Nlag = int(figv[1]) colbar = gen.auto_val(figv[2], 'rainbow') check_colorBar(colbar) cbarfmt = figv[3] cbaror = gen.auto_val(figv[4], 'vertical') ltype = gen.str_list_rep(figv[5],'@',Nvalues) lwidth = gen.str_list_rep(figv[6],'@',Nvalues) mtype = gen.str_list_rep(figv[7],'@',Nvalues) msize = gen.str_list_rep(figv[8],'@',Nvalues) my_cmap = plt.cm.get_cmap(colbar) tminv = np.min(tvals[iv]) tmaxv = np.max(tvals[iv]) norm = mpl.colors.Normalize(tminv,tmaxv) if labels is not None and labels[iv] != 'None': for it in range(dimt-Nlag-1): clv = my_cmap(norm(tvalues[it])) if it == 0: plt.plot([xvs[it],xvs[it+1]], [yvs[it+Nlag],yvs[it+Nlag+1]], \ ltype[iv], color=clv, linewidth=np.float(lwidth[iv]), \ marker=mtype[iv], markersize=np.float(msize[iv]), \ label=gen.latex_text(labels[iv])) else: plt.plot([xvs[it],xvs[it+1]], [yvs[it+Nlag],yvs[it+Nlag+1]], \ ltype[iv], color=clv, linewidth=np.float(lwidth[iv]), \ marker=mtype[iv], markersize=np.float(msize[iv])) else: for it in range(dimt-Nlag): clv = my_cmap(norm(it)) plt.plot([xvs[it],xvs[it+1]], [yvs[it+Nlag],yvs[it+Nlag+1]], \ ltype[iv], color=clv, linewidth=lwidth[iv], marker=mtype[iv], \ markersize=msize[iv]) elif figtypen == 'simplepts': expectargs = "'simplepts',[Nlag],[col],[type],[size]" check_arguments(fname + " & 'simplepts'",figtype,expectargs,',') Nlag = int(figv[1]) if figv[2] == 'auto': col = colorsauto else: col = gen.str_list_rep(figv[2],'@',Nvalues) mark = gen.str_list_rep(figv[3],'@',Nvalues) size = gen.str_list_rep(figv[4],'@',Nvalues) if labels is not None and labels[iv] != 'None': plt.plot(xvs[0:dimt-Nlag], yvs[Nlag:dimt], ',', color=col[iv], \ marker=mark[iv], markersize=size[iv], \ label=gen.latex_text(labels[iv])) else: plt.plot(xvs[0:dimt-Nlag], yvs[Nlag:dimt], ',', color=col[iv], \ marker=mark[iv], markersize=size[iv]) # Computing correlation corr, p_value = sts.pearsonr(xvs[0:dimt-Nlag], yvs[Nlag:dimt]) txt='corr= ' + '{0:.3g}'.format(corr) + ' p: ' + '{0:.2g}'.format(p_value) plt.annotate(txt,xy=(0.95,0.05*(Nvalues-iv)), xycoords='figure fraction',\ color=col[iv], fontsize=lsiz, horizontalalignment='right') else: print errormsg print ' ' + fname + ": time-lag figure named '" + figtype + "' not ready !!" print ' availabe ones:', ['repeatPeriod', 'shadTline', 'simplepts'] quit(-1) if axistype == 'box': print infmsg print ' ' + fname + ': plotting with around axes' elif axistype == 'centered': # Drawing centered axes # From http://stackoverflow.com/questions/31556446/drawing-axis-in-the-middle-of-the-figue-in-python # Move left y-axis and bottim x-axis to centre, passing through (0,0) ax.spines['left'].set_position('center') ax.spines['bottom'].set_position('center') # Eliminate upper and right axes ax.spines['right'].set_color('none') ax.spines['top'].set_color('none') else: print errormsg print ' ' + fname + ": axis plotting type '" + axistype + "' not ready !!" print ' available ones:', ['box', 'centered'] quit(-1) plt.xticks(dimxt, list(dimxl), rotation=xaxv[3]) plt.yticks(dimyt, list(dimyl), rotation=yaxv[3]) if preu != 'None': plt.xlabel(gen.latex_text(prelab) + ' (' + units_lunits(preu) + ')') else: plt.xlabel(gen.latex_text(prelab)) if futu != 'None': plt.ylabel(gen.latex_text(futlab) + ' (' + units_lunits(futu) + ')') else: plt.xlabel(gen.latex_text(futlab)) ax.xaxis.set_label_coords(0.5, -0.025) ax.yaxis.set_label_coords(-0.025, 0.5) plt.xlim(prerange[0], prerange[1]) plt.ylim(futrange[0], futrange[1]) if labels is not None: plt.legend(loc=lloc, prop={'size':lsiz}) # Colorbar if gen.searchInlist(['repeatPeriod', 'shadTline'], figtypen): # FROM: http://stackoverflow.com/questions/8342549/matplotlib-add-colorbar-to-a-sequence-of-line-plots # For matplotlib v1.3 or greater the code becomes: sm = plt.cm.ScalarMappable(cmap=colbar, norm=norm) # fake up the array of the scalar mappable. Urgh... sm._A = [] #cbar = plt.colorbar(sm) if cbaror == 'horizontal': cbar = plt.colorbar(sm, ticks=[tpos], format=cbarfmt,orientation=cbaror) cbar.ax.set_xticklabels(tlab,rotation=90) else: print warnmsg print ' ' + fname + ": This is odd, because in 'vertical' mode does " + \ "not work the re-labelling of the ticking!" cbar = plt.colorbar(sm, ticks=[tpos], format=cbarfmt, orientation=cbaror) cbar.ax.set_xticklabels(tlab) cbar.set_label(gen.latex_text(tname)) plt.title(gen.latex_text(gtit)) output_kind(kfig, figname, ifclose) return def plot_TimeEnsembles(linevals, ensvals, ltimevals, etimevals, xaxv, yaxv, \ valuesvals, Lcol, Ltype, Lwidth, Lmarker, Lsizem, labels, figtype, tname, tpos, \ tlabs, gtit, lloc, lsiz, kfig, figname, ofile, ifclose): """ Function to plot a of an Ensemble of values with a time-axis linevals= list of values to be plotted with lines ensvals= list of values of the ensemble ltimevals= list with the time-values of the lines etimevals= list with the time-values of the ensemble values [x/y]axv= values at the axes x and y valuesvals = list with characteristics of the values axis axisvalues= in which axis should the values be plotted ('x', 'y') valueslab= label of the axis values valuesunits= units of the axis values valrange: range of the axis values figtype= [kindname],[valueskind] kind of time-Ensembles plot 'cloud',[color],[limits]: ensembles values as a cloud [color]: name of the color to use ('auto' for '#DDDDDD') [limits]: which stadistics to use for the plot ('auto' for extremes) '5quantile': 5quantile,95quantile of the values 'direct': below and up values are tacking directly from the provided data 'extremes': min,max of the values 'stddev': standard deviation fo the values (only available if there is one line) 'spaghetti',[color],[width],[type]: a line for each member [color]: name of the color to use for all lines ('auto' for '#DDDDDD') [width]: width of the line to use for all lines ('auto' for 0.5) [type]: type of the line to use for all lines ('auto' for '-') Lcol= '@' list of color for the lines (single value for the same) Ltype= '@' list of types for the lines (single value for the same) Lwidth= '@' list of widths for the lines (single value for the same) Lmarker= '@' list of markers for the lines (single value for the same) Lsizem= '@' list of size markers for the lines (single value for the same) labels= list of labels for legend of lines (None for no legend, and 'None' for no specific label) tname= label of the time-axis tpos= position of the time-ticks tlabs= labels of the time-ticks gtit= title of the figure lloc= location of the legend (0, autmoatic) 1: 'upper right', 2: 'upper left', 3: 'lower left', 4: 'lower right', 5: 'right', 6: 'center left', 7: 'center right', 8: 'lower center', 9: 'upper center', 10: 'center' lsiz= font size of the legend kfig= kind of output: pdf, png, ps figname= name of the figure ofile= object of the output file with the ensemble statistics (None if it is not required) ifclose= whether figure should be closed """ fname = 'plot_TimeEnsembles' # List of available limits to compute from the ensemble availim = ['5quantile', 'extremes', 'stddev'] Nlvalues = len(linevals) Nevalues = len(ensvals) print gen.infmsg print ' ' + fname + ': plotting ', Nlvalues, 'lines', Nevalues, \ 'ensemble members' dyn = gen.fillValue dyx = -gen.fillValue for iv in range(Nlvalues): minv = np.min(linevals[iv]) maxv = np.max(linevals[iv]) if minv < dyn: dyn = minv if maxv > dyx: dyx = maxv for iv in range(Nevalues): minv = np.min(ensvals[iv]) maxv = np.max(ensvals[iv]) if minv < dyn: dyn = minv if maxv > dyx: dyx = maxv if yaxv[0] == 'pretty': dimyt = np.array(gen.pretty_int(dyn,dyx,yaxv[2])) dimyl = np.array(dimyt, dtype=str) elif yaxv[0] == 'Nfix': dimyt = np.arange(dyn,dyx,(dyx-dyn)/(yaxv[2]+1)) dimyl = np.arange(dyn,dyx,(dyx-dyn)/Lymaxvals) axytype='fixpixel' elif yaxv[0] == 'Vfix': dynvfix = int(dyn/yaxv[2]) dimyt = np.arange(dynvfix*xaxv[2],dyx,yaxv[2]) axytype='data' else: print errormsg print ' ' + fname + ": x-xais style '" + xaxv[0] + "' not ready !!" print ' available ones: ', axstyles quit(-1) # kind of ensembles figure: figv = figtype.split(',') figtypen = figv[0] # Ensemble values to use in the figure dimt = etimevals[0].shape[len(etimevals[0].shape)-1] evs = np.zeros((dimt,Nevalues), dtype=np.float) for iv in range(Nevalues): xvs = ensvals[iv] if xvs.shape[0] != dimt: print errormsg print ' ' +fname+ ': ensemble values', iv, 'has different number:', \ xvs.shape[0], 'of time-steps:', dimt ,'!!' quit(-1) evs[:,iv] = xvs plt.rc('text', usetex=True) fig = plt.subplot(1,1,1) if figtypen == 'cloud': expectargs = "'cloud',[color],[limits]" gen.check_arguments(fname + " & 'cloud'",figtype, expectargs,',') col = gen.auto_val(figv[1], '#DDDDDD') limits = gen.auto_val(figv[2], 'extremes') cloudlims = np.zeros((dimt,2), dtype=np.float) # Computing limits of the data-ensemble if limits == '5quantile': for it in range(dimt): quants = gen.mask_quantiles(evs[it,:], 20, Notenough=True) cloudlims[it,0] = quants[1]-100. cloudlims[it,1] = quants[18]+100. Llimits = '5quantile,95quantile of the values of the ensemble' glimits = '5-95 quantile' elif limits == 'direct': for it in range(dimt): cloudlims[it,0] = evs[it,0] cloudlims[it,1] = evs[it,1] Llimits = 'first 2 values' glimits = 'values' elif limits == 'extremes': for it in range(dimt): cloudlims[it,0] = evs[it,:].min() cloudlims[it,1] = evs[it,:].max() Llimits = 'min,max of the values of the ensemble' glimits = 'min,max' elif limits == 'stddev': if Nlvalues != 1: print errormsg print ' ' +fname+ ": with ensemble-limits '" + limits + "' only " + \ '1-line is allowed', Nlvalues, 'provided !!' quit(-1) lvals = linevals[0] for it in range(dimt): sttdev = evs[it,:].std() cloudlims[it,0] = lvals[it] - sttdev cloudlims[it,1] = lvals[it] + sttdev Llimits = 'val+/-standard deviation of the values of the ensemble' glimits = 'val$\pm\sigma$' else: print errormsg print ' ' +fname+ ": type of cloud-limits '" + limits + "' not ready !!" print ' available ones:', availim quit(-1) if valuesvals[0] == 'x': print errrormsg print ' ' + fname + ": for '" + figtypen + "' there is no way to use " +\ "'x'-axis as axis-value !!" print " matplotlib: 'fill_between' does not allow it !!" quit(-1) else: plt.fill_between(etimevals[0], cloudlims[:,0], cloudlims[:,1], \ facecolor=col, label=glimits) elif figtypen == 'spaghetti': expectargs = "'spaghetti',[color],[width],[type]" gen.check_arguments(fname + " & 'spaghetti'",figtype, expectargs,',') col = gen.auto_val(figv[1], '#DDDDDD') width = gen.auto_val(figv[2], 0.5) ltype = gen.auto_val(figv[3], '-') if valuesvals[0] == 'x': for iv in range(Nevalues): plt.plot(ensvals[iv], etimevals[iv], ltype, color=col, linewidth=width) else: for iv in range(Nevalues): plt.plot(etimevals[iv], ensvals[iv], ltype, color=col, linewidth=width) else: print errormsg print ' ' + fname + ": '" + figtypen + "' not ready !!" print ' available ones:', ['cloud', 'spaghetti'] quit(-1) fig = plt.subplot(1,1,1) # Plotting lines lcols = gen.str_list_rep(Lcol, '@', Nlvalues) ltypes = gen.str_list_rep(Ltype, '@', Nlvalues) lwdths = gen.str_list_rep(Lwidth, '@', Nlvalues) mtypes = gen.str_list_rep(Lmarker, '@', Nlvalues) msizes = gen.str_list_rep(Lsizem, '@', Nlvalues) for iv in range(Nlvalues): if valuesvals[0] == 'x': xvs = linevals[iv] yvs = ltimevals[iv] else: xvs = ltimevals[iv] yvs = linevals[iv] if labels is not None and labels[iv] != 'None': plt.plot(xvs, yvs, ltypes[iv], color=lcols[iv], linewidth=lwdths[iv], \ marker=mtypes[iv], markersize=msizes[iv], label=labels[iv]) else: plt.plot(xvs, yvs, ltypes[iv], color=lcols[iv], linewidth=lwdths[iv], \ marker=mtypes[iv], markersize=msizes[iv]) # Axis vrange = valuesvals[3] if valuesvals[0] == 'x': plt.xticks(dimyt, list(dimyl), rotation=yaxv[3]) plt.yticks(tpos, tlabs, rotation=xaxv[3]) if valuesvals[2] != 'None': plt.xlabel(gen.latex_text(valuesvals[1]) + ' (' + \ units_lunits(valuesvals[2]) + ')') else: plt.xlabel(gen.latex_text(valuesvals[1])) plt.ylabel(gen.latex(tname)) plt.xlim(vrange[0], vrange[1]) plt.ylim(tpos[0], tpos[len(tpos)-1]) else: plt.xticks(tpos, tlabs, rotation=xaxv[3]) plt.yticks(dimyt, list(dimyl), rotation=yaxv[3]) plt.xlabel(gen.latex_text(tname)) if valuesvals[2] != 'None': plt.ylabel(gen.latex_text(valuesvals[1]) + ' (' + \ units_lunits(valuesvals[2]) + ')') else: plt.ylabel(gen.latex_text(valuesvals[1])) plt.xlim(tpos[0], tpos[len(tpos)-1]) plt.ylim(vrange[0], vrange[1]) if labels is not None: plt.legend(loc=lloc, prop={'size':lsiz}) plt.title(gen.latex_text(gtit)) output_kind(kfig, figname, ifclose) # Creation of the output file if ofile is not None: # Data of the lines newvar = ofile.createVariable('vals', 'f4', ('time','data'), \ fill_value=gen.fillValueF) basicvardef(newvar, 'vals', 'direct data plotted with lines', valuesvals[2]) newvar[:] = np.array(linevals) # Data of the ensemble newvar = ofile.createVariable('ensvals', 'f4', ('time','ensemble'), \ fill_value=gen.fillValueF) basicvardef(newvar, 'ensvals', 'data of the ensemble', valuesvals[2]) newvar[:] = evs # cloud particularities if figtypen == 'cloud': newvar.setncattr('ensemble_limits', Llimits) newdim = ofile.createDimension('cloudlims',2) newvar = ofile.createVariable('cloudlims', 'f4', ('time','cloudlims'), \ fill_value=gen.fillValueF) basicvardef(newvar, 'cloudlims', 'limits of the cloud plot', \ valuesvals[2]) newvar[:] = cloudlims[:] return def plot_cycle(vals, tvals, xaxv, yaxv, axkind, axistype, axlab, axunits, axrng, \ cyc, cyc0, cyck, labs, cycp, cycl, tn, tpos, tlabs, gtit, lloc, lsiz, kfig, fn,\ ifclose): """ Function to plot a cycle vals= list of cyclic values tvals= list with the time-values [x/y]axv= values at the axes x and y axkind= in which axis should the values be plotted ('x', 'y') axlab= label of the axis values axunits= units of the axis values axrng= range of the axis values cyc= number of time steps of a whole cycle cyc0= initial position of time steps whithin the cycle cyck=[kindname],[valueskind] kind of cycle plot 'cloud',[color],[cbaror],[cbarfmt],[marker],[markersize]: values as a cloud of points [color]: name of the colorbar to use changing after the end of each cycle ('auto' for 'rainbow') [cbaror]: orientation of the colorbar ('auto' for vertical) [cbarfmt]: format of the numbers in the colorbar ('auto' for %5.2g) [marker]: '@' list of kind of marker (single value for the same for all) [markersize]: '@' list of size of marker (single value for the same for all) 'lines',[color],[width],[type]: values a continuous line [color]: name of the colorbar to use changing after the end of each cycle ('auto' for 'rainbow') [width]: width of the line to use for all lines ('auto' for 0.5) [type]: type of the line to use for all lines ('auto' for '-') labs= list of labels for legend of lines (None for no legend, and 'None' for no specific label) cycp= position of the cycle ticks cycl= labels of the cycle ticks tn= label of the time-axis tpos= position of the time-ticks tlabs= labels of the time-ticks gtit= title of the figure lloc= location of the legend (0, autmoatic) 1: 'upper right', 2: 'upper left', 3: 'lower left', 4: 'lower right', 5: 'right', 6: 'center left', 7: 'center right', 8: 'lower center', 9: 'upper center', 10: 'center' lsiz= font size of the legend kfig= kind of output: pdf, png, ps fn= name of the figure ifclose= whether figure should be closed """ fname = 'plot_cycle' Nvalues = len(vals) dyn = axrng[0] dyx = axrng[1] axstyles = ['pretty', 'Nfix', 'Stringlist', 'Vfix'] if yaxv[0] == 'pretty': dimyt = np.array(gen.pretty_int(dyn,dyx,yaxv[2])) dimyl = np.array(dimyt, dtype=str) elif yaxv[0] == 'Nfix': dimyt = np.arange(dyn,dyx,(dyx-dyn)/(yaxv[2]+1)) dimyl = np.arange(dyn,dyx,(dyx-dyn)/Lymaxvals) axytype='fixpixel' elif yaxv[0] == 'Vfix': dynvfix = int(dyn/yaxv[2]) dimyt = np.arange(dynvfix*xaxv[2],dyx,yaxv[2]) axytype='data' else: print errormsg print ' ' + fname + ": x-xais style '" + xaxv[0] + "' not ready !!" print ' available ones: ', axstyles quit(-1) # kind of cycle figure: figv = cyck.split(',') figtypen = figv[0] # Computing cycling x-positions cycx = [] for it in range(cyc): itx = cyc0 + it if itx <= cyc/2: cycx.append(itx) else: if cyc-itx > 0: cycx.append(cyc-itx) else: cycx.append(np.abs(cyc-itx)) cycx.append(cyc0) print ' ' + fname + ': cycle positions:', cycx plt.rc('text', usetex=True) fig, ax = plt.subplots(1) for iv in range(Nvalues): xvs = vals[iv] dimt = len(xvs) Ncyc = dimt/cyc # Normalizing position of the ticks if iv == 0: tminv = np.min(tvals[iv]) tmaxv = np.max(tvals[iv]) tpos = (tpos-tminv)*Ncyc/(tmaxv-tminv) if figtypen == 'cloud': expectargs = 'cloud,[color],[cbaror],[cbarfmt],[marker],[marekersize]' check_arguments(fname + " & 'cloud'", cyck, expectargs,',') colbar = gen.auto_val(figv[1], 'rainbow') cbaror = gen.auto_val(figv[2], 'vertical') cbarfmt = gen.auto_val(figv[3], '%5.2g') mtype = gen.str_list_rep(figv[4],'@',Nvalues) msize = gen.str_list_rep(figv[5],'@',Nvalues) my_cmap = plt.cm.get_cmap(colbar) norm = mpl.colors.Normalize(0.,Ncyc) if labs is not None and labs[iv] != 'None': for ic in range(Ncyc): clv = my_cmap(norm(ic*1.)) for it in range(cyc): Tt = cyc*ic+it if Tt + 1 > dimt-1: break if ic == 0 and it == 0: if axkind == 'y': plt.plot(cycx[it], xvs[Tt], color=clv, \ marker=mtype[iv], markersize=np.float(msize[iv]), \ label=gen.latex_text(labs[iv]), zorder=-10) else: plt.plot(xvs[Tt], cycx[it], color=clv, \ marker=mtype[iv], markersize=np.float(msize[iv]), \ label=gen.latex_text(labs[iv]), zorder=-10) else: if axkind == 'y': plt.plot(cycx[it], xvs[Tt], color=clv, \ marker=mtype[iv],markersize=np.float(msize[iv]), \ zorder=-10) else: plt.plot(xvs[Tt], cycx[it], color=clv, \ marker=mtype[iv],markersize=np.float(msize[iv]), \ zorder=-10) else: for ip in range(Ncyc): clv = my_cmap(norm(ip*1.)) for it in range(cyc): Tt = cyc*ic+it if Tt + 1 > dimt-1: break if axkind == 'y': plt.plot(cycx[it], xvs[Tt], color=clv, marker=mtype[iv], \ markersize=np.float(msize[iv]), zorder=-10) else: plt.plot(xvs[Tt], cycx[it], color=clv, marker=mtype[iv], \ markersize=np.float(msize[iv]), zorder=-10) # Plotting with lines elif figtypen == 'lines': expectargs = 'lines,[color],[cbaror],[cbarfmt],[linetype],[linewidth]' check_arguments(fname + " & 'cloud'", cyck, expectargs,',') colbar = gen.auto_val(figv[1], 'rainbow') cbaror = gen.auto_val(figv[2], 'vertical') cbarfmt = gen.auto_val(figv[3], '%5.2g') ltype = gen.str_list_rep(figv[4],'@',Nvalues) lwdth = gen.str_list_rep(figv[5],'@',Nvalues) my_cmap = plt.cm.get_cmap(colbar) tminv = np.min(tvals[iv]) tmaxv = np.max(tvals[iv]) norm = mpl.colors.Normalize(0.,Ncyc) if labs is not None and labs[iv] != 'None': for ic in range(Ncyc): clv = my_cmap(norm(ic*1.)) for it in range(cyc): Tt = cyc*ic+it if Tt + 1 > dimt-1: break xl = [cycx[it], cycx[it+1]] yl = [xvs[Tt], xvs[Tt+1]] if ic == 0 and it == 0: if axkind == 'y': plt.plot(xl, yl, ltype[iv], color=clv, \ linewidth=np.float(lwdth[iv]), \ label=gen.latex_text(labs[iv]), zorder=-10) else: plt.plot(yl, xl, marker=ltype[iv], color=clv, \ linewidth=np.float(lwdth[iv]), \ label=gen.latex_text(labs[iv]), zorder=-10) else: if axkind == 'y': plt.plot(xl, yl, ltype[iv], color=clv, \ linewidth=np.float(lwdth[iv]), zorder=-10) else: plt.plot(yl, xl, ltype[iv], color=clv, \ linewidth=np.float(lwdth[iv]), zorder=-10) else: for ip in range(Ncyc): clv = my_cmap(norm(ip*1.)) for it in range(cyc): Tt = cyc*ic+it if Tt + 1 > dimt-1: break xl = [cycx[it], cycx[it+1]] yl = [xvs[Tt], xvs[Tt+1]] if axkind == 'y': plt.plot(xl, yl, ltype[iv], color=clv, \ linewidth=np.float(lwdth[iv]), zorder=-10) else: plt.plot(yl, xl, ltype[iv], color=clv, \ linewidth=np.float(lwdth[iv]), zorder=-10) else: print errormsg print ' ' + fname + ": cycle figure named '" + figtypen + "' not reay !!" print ' availabe ones:', ['cloud', 'lines'] quit(-1) if axistype == 'box': print gen.infmsg print ' ' + fname + ': plotting with around axes' elif axistype == 'centered': # Drawing centered axes # From http://stackoverflow.com/questions/31556446/drawing-axis-in-the-midde-of-the-figue-in-python # Move left y-axis and bottim x-axis to centre, passing through (0,0) ax.spines['left'].set_position('center') ax.spines['bottom'].set_position('center') # Eliminate upper and right axes ax.spines['right'].set_color('none') ax.spines['top'].set_color('none') ax.xaxis.set_label_coords(0.5, -0.025) ax.yaxis.set_label_coords(-0.025, 0.5) else: print errormsg print ' ' + fname + ": axis plotting type '" + axistype + "' not ready !!" print ' available ones:', ['box', 'centered'] quit(-1) if axkind == 'y': plt.xticks(cycp, cycl, rotation=xaxv[3]) plt.yticks(dimyt, list(dimyl), rotation=yaxv[3]) if axunits != 'None': plt.ylabel(gen.latex_text(axlab) + ' (' + units_lunits(axunits) + ')') else: plt.ylabel(gen.latex_text(axlab)) plt.xlim(-1., cyc/2.+1) plt.ylim(axrng[0], axrng[1]) else: plt.xticks(dimyt, list(dimyl), rotation=yaxv[3]) plt.yticks(cycp, cycl, rotation=xaxv[3]) if axunits != 'None': plt.xlabel(gen.latex_text(axlab) + ' (' + units_lunits(axunits) + ')') else: plt.xlabel(gen.latex_text(axlab)) plt.xlim(axrng[0], axrng[1]) plt.ylim(-1., cyc/2.+1) if labs is not None: plt.legend(loc=lloc, prop={'size':lsiz}) # Colorbar if gen.searchInlist(['cloud', 'lines'], figtypen): # FROM: http://stackoverflow.com/questions/8342549/matplotlib-add-colorbar-to-a-sequence-of-line-plots # For matplotlib v1.3 or greater the code becomes: sm = plt.cm.ScalarMappable(cmap=colbar, norm=norm) # fake up the array of the scalar mappable. Urgh... sm._A = [] #cbar = plt.colorbar(sm) if cbaror == 'horizontal': cbar = plt.colorbar(sm, ticks=list(tpos), format=cbarfmt, orientation=cbaror) cbar.ax.set_xticklabels(tlabs,rotation=90) else: print warnmsg print ' ' + fname + ": This is odd, because in 'vertical' mode does " + \ "not work the re-labelling of the ticking!" cbar = plt.colorbar(sm, ticks=[tpos], format=cbarfmt, orientation=cbaror) cbar.ax.set_xticklabels(tlabs) cbar.set_label(gen.latex_text(tn)) plt.xticks.zorder=-2 plt.xticks.zorder=-2 plt.title(gen.latex_text(gtit)) output_kind(kfig, fn, ifclose) return def multi_plot_2D_shadow(lvarsv, dimxv, dimyv, dimxu, dimyu, xaxv, yaxv, dimn, \ cbarv, vs, uts, kfig, reva, mapv, labs, Ncol, Nrow, ftit, ifclose): """ plot of multiple 2D shadowing variables sharing colorbar lvarsv= list of 2D values to plot with shading dim[x/y]v = list of values at the axes of x and y dim[x/y]u = units at the axes of x and y xaxv= list with the x-axis paramteres [style, format, number and orientation] yaxv= list with the y-axis paramteres [style, format, number and orientation] dimn= dimension names to plot cbarv= list with the parameters of the color bar [colorbar, cbarfmt, cbaror] colorbar: name of the color bar to use cbarfmt: format of the numbers in the colorbar cbaror: orientation of the colorbar vs= minmum and maximum values to plot in shadow or: 'Srange': for full range 'Saroundmean@val': for mean-xtrm,mean+xtrm where xtrm = np.min(mean-min@val,max@val-mean) 'Saroundminmax@val': for min*val,max*val 'Saroundpercentile@val': for median-xtrm,median+xtrm where xtrm = np.min(median-percentile_(val), percentile_(100-val)-median) 'Smean@val': for -xtrm,xtrm where xtrm = np.min(mean-min*@val,max*@val-mean) 'Smedian@val': for -xtrm,xtrm where xtrm = np.min(median-min@val,max@val-median) 'Spercentile@val': for -xtrm,xtrm where xtrm = np.min(median-percentile_(val), percentile_(100-val)-median) uts= units of the variable to shadow vtit= title of the variable kfig= kind of figure (jpg, pdf, png) reva= ('|' for combination) * 'transpose': reverse the axes (x-->y, y-->x) * 'flip'@[x/y]: flip the axis x or y mapv= map characteristics: [proj],[res] see full documentation: http://matplotlib.org/basemap/ [proj]: projection * 'cyl', cilindric * 'lcc', lambert conformal [res]: resolution: * 'c', crude * 'l', low * 'i', intermediate * 'h', high * 'f', full labs: list of consecutive labels for each figure ftit: global title of the figure Ncol: number of column panels Nrow: number of rows of panels ifclose= boolean value whether figure should be close (finish) or not """ ## import matplotlib as mpl ## mpl.use('Agg') ## import matplotlib.pyplot as plt fname = 'multi_plot_2D_shadow' # print dimyv[73,21] # dimyv[73,21] = -dimyv[73,21] # print 'Lluis dimsv: ',np.min(dimxv), np.max(dimxv), ':', np.min(dimyv), np.max(dimyv) if type(lvarsv) == type('S') and varsv == 'h': print fname + '_____________________________________________________________' print multi_plot_2D_shadow.__doc__ quit() # Getting the right lon values for plotting if mapv is not None: dimxv = np.where(dimxv > 180., dimxv-360., dimxv) # Axis ticks # Usually axis > x must be the lon, thus... dimxv0 = dimxv.copy() dimyv0 = dimyv.copy() dxn = dimxv.min() dxx = dimxv.max() dyn = dimyv.min() dyx = dimyv.max() if xaxv[0] == 'pretty': dimxt0 = np.array(gen.pretty_int(dxn,dxx,xaxv[2])) elif xaxv[0] == 'Nfix': dimxt0 = np.arange(dxn,dxx,(dxx-dxn)/(1.*xaxv[2])) elif xaxv[0] == 'Vfix': dimxt0 = np.arange(0,dxx,xaxv[2]) if yaxv[0] == 'pretty': dimyt0 = np.array(gen.pretty_int(dyn,dyx,yaxv[2])) elif yaxv[0] == 'Nfix': dimyt0 = np.arange(dyn,dyx,(dyx-dyn)/(1.*yaxv[2])) elif yaxv[0] == 'Vfix': dimyt0 = np.arange(0,dyx,yaxv[2]) dimxl0 = [] for i in range(len(dimxt0)): dimxl0.append('{:{style}}'.format(dimxt0[i], style=xaxv[1])) dimyl0 = [] for i in range(len(dimyt0)): dimyl0.append('{:{style}}'.format(dimyt0[i], style=yaxv[1])) dimxT0 = variables_values(dimn[0])[0] + ' (' + units_lunits(dimxu) + ')' dimyT0 = variables_values(dimn[1])[0] + ' (' + units_lunits(dimyu) + ')' if mapv is not None: pixkind = 'data' else: # No following data values dimxt0 = np.arange(len(dimxt0),dtype=np.float)/(len(dimxt0)) dimyt0 = np.arange(len(dimyt0),dtype=np.float)/(len(dimyt0)) pixkind = 'fixpixel' if reva is not None: varsv, dimxv, dimyv, dimxt, dimyt, dimxl, dimyl, dimxT, dimyT = \ transform(varsv, reva, dxv=dimxv0, dyv=dimyv0, dxt=dimxt0, dyt=dimyt0, \ dxl=dimxl0, dyl=dimyl0, dxtit=dimxT0, dytit=dimyT0) else: dimxv = dimxv0 dimyv = dimyv0 dimxt = dimxt0 dimyt = dimyt0 dimxl = dimxl0 dimyl = dimyl0 dimxT = dimxT0 dimyT = dimyT0 if len(dimxv[:].shape) == 3: xdims = '1,2' elif len(dimxv[:].shape) == 2: xdims = '0,1' elif len(dimxv[:].shape) == 1: xdims = '0' if len(dimyv[:].shape) == 3: ydims = '1,2' elif len(dimyv[:].shape) == 2: ydims = '0,1' elif len(dimyv[:].shape) == 1: ydims = '0' lon0, lat0 = dxdy_lonlat(dimxv,dimyv, xdims, ydims) if not mapv is None: map_proj=mapv.split(',')[0] map_res=mapv.split(',')[1] dx = lon0.shape[1] dy = lat0.shape[0] nlon = np.min(lon0) xlon = np.max(lon0) nlat = np.min(lat0) xlat = np.max(lat0) lon2 = lon0[dy/2,dx/2] lat2 = lat0[dy/2,dx/2] print 'lon2:', lon2, 'lat2:', lat2, 'SW pt:', nlon, ',', nlat, 'NE pt:', \ xlon, ',', xlat if map_proj == 'cyl': m = Basemap(projection=map_proj, llcrnrlon=nlon, llcrnrlat=nlat, \ urcrnrlon=xlon, urcrnrlat= xlat, resolution=map_res) elif map_proj == 'lcc': m = Basemap(projection=map_proj, lat_0=lat2, lon_0=lon2, llcrnrlon=nlon, \ llcrnrlat=nlat, urcrnrlon=xlon, urcrnrlat= xlat, resolution=map_res) else: print errormsg print ' ' + fname + ": map projection '" + map_proj + "' not defined!!!" print ' available: cyl, lcc' quit(-1) x,y = m(lon0,lat0) if cbarv[0] == 'gist_gray': m.drawcoastlines(color="red") else: m.drawcoastlines() meridians = gen.pretty_int(nlon,xlon,xaxv[2]) m.drawmeridians(meridians,labels=[True,False,False,True]) parallels = gen.pretty_int(nlat,xlat,yaxv[2]) m.drawparallels(parallels,labels=[False,True,True,False]) else: # No following data values x = (dimxv-np.min(dimxv))/(np.max(dimxv) - np.min(dimxv)) y = (dimyv-np.min(dimyv))/(np.max(dimyv) - np.min(dimyv)) # Changing limits of the colors vsend = graphic_range(vs,lvarsv) # Number of panels Npanels = len(lvarsv) if Ncol*Nrow != Npanels: print errormsg print ' ' + fname + ': no coincident number of panels:', Npanels, \ 'with provied distribution of them:', Ncol, Nrow plt.rc('text', usetex=True) fig, axes = plt.subplots(Nrow, Ncol) irow=0 icol=0 for iv in range(Npanels): varsv = lvarsv[iv] if len(varsv.shape) != 2: print errormsg print ' ' + fname + ': wrong variable shadow rank:', varsv.shape, \ 'is has to be 2D!!' quit(-1) if len(axes.shape) > 1: axes[irow,icol] = plt.subplot(Nrow ,Ncol, iv+1) else: if Ncol > 1: axes[icol] = plt.subplot(Nrow ,Ncol, iv+1) elif Nrow > 1: axes[irow] = plt.subplot(Nrow ,Ncol, iv+1) im = plt.pcolormesh(x, y, varsv, cmap=plt.get_cmap(cbarv[0]), vmin=vsend[0], \ vmax=vsend[1]) if not mapv is None: m.drawcoastlines() m.drawmeridians(meridians,labels=[True,False,False,True]) m.drawparallels(parallels,labels=[False,True,True,False]) if irow == Nrow -1: plt.xlabel('W-E') if icol == 0: plt.ylabel('S-N') else: plt.xlabel(dimxT) plt.ylabel(dimyT) plt.xticks(dimxt, dimxl, rotation=xaxv[3]) plt.yticks(dimyt, dimyl, rotation=yaxv[3]) plt.axis([x.min(), x.max(), y.min(), y.max()]) graphtit = gen.latex_text(labs[iv].replace('!', ' ')) plt.title(gen.latex_text(graphtit)) icol = icol + 1 if icol > Ncol-1: irow = irow + 1 icol = 0 fig.subplots_adjust(right=0.8, hspace=0.4) cbar_ax = fig.add_axes([0.86, 0.25, 0.03, 0.50]) if cbarv[2] == 'horizontal': cbar = fig.colorbar(im, cax=cbar_ax, format=cbarv[1],orientation=cbarv[2]) # From: http://stackoverflow.com/questions/32050030/rotation-of-colorbar-tick-labels-in-matplotlib ticklabels= cbar.ax.get_xticklabels() Nticks = len(ticklabels) ticklabs = [] for itick in range(Nticks): ticklabs.append(ticklabels[itick].get_text()) cbar.ax.set_xticklabels(ticklabs,rotation=90) else: cbar = fig.colorbar(im, cax=cbar_ax, format=cbarv[1],orientation=cbarv[2]) #fig.colorbar(im, cax=cbar_ax) # units labels ulab = units_lunits(uts) cbar_ax.set_label(ulab) plt.annotate(ulab, xy=(0.96,0.5), xycoords='figure fraction', rotation=90) cbar_ax.tick_params(labelsize=8) plt.suptitle(ftit) figname = 'multi_2Dfields_shadow' output_kind(kfig, figname, ifclose) return def movie_2D_shadow(varsv, dimT, vnames, dimxv, dimyv, dimxu, dimyu, xaxv, yaxv, \ dimn, cbarv, vs, uts, ltit, kfig, reva, mapv, framesec, kmov): """ Plot of a 2D field with shadow varsv= 3D values to plot each frame with shading dimT= number of the dimension to be used as time-loop vnames= variable names for the figure dim[x/y]v = values at the axes of x and y dim[x/y]u = units at the axes of x and y xaxv= list with the x-axis paramteres [style, format, number and orientation] yaxv= list with the y-axis paramteres [style, format, number and orientation] dimn= dimension names to plot cbarv= list with the parameters of the color bar [colorbar, cbarfmt, cbaror] colorbar: name of the color bar to use cbarfmt: format of the numbers in the colorbar cbaror: orientation of the colorbar vs= minmum and maximum values to plot in shadow or: 'Srange': for full range 'Saroundmean@val': for mean-xtrm,mean+xtrm where xtrm = np.min(mean-min@val,max@val-mean) 'Saroundminmax@val': for min*val,max*val 'Saroundpercentile@val': for median-xtrm,median+xtrm where xtrm = np.min(median-percentile_(val), percentile_(100-val)-median) 'Smean@val': for -xtrm,xtrm where xtrm = np.min(mean-min*@val,max*@val-mean) 'Smedian@val': for -xtrm,xtrm where xtrm = np.min(median-min@val,max@val-median) 'Spercentile@val': for -xtrm,xtrm where xtrm = np.min(median-percentile_(val), percentile_(100-val)-median) uts= units of the variable to shadow ltit= list of titles for each frame kfig= kind of figure (jpg, pdf, png) reva= ('|' for combination) * 'transpose': reverse the axes (x-->y, y-->x) * 'flip'@[x/y]: flip the axis x or y mapv= map characteristics: [proj],[res] see full documentation: http://matplotlib.org/basemap/ [proj]: projection * 'cyl', cilindric * 'lcc', lambert conformal [res]: resolution: * 'c', crude * 'l', low * 'i', intermediate * 'h', high * 'f', full fremessec= frames per second of the output movie kmov= kind of movie putput (mp4) """ import matplotlib.animation as manimation fname = 'movie_2D_shadow' ofile = "movie_2D_shadow." + kmov if type(varsv) == type('S') and varsv == 'h': print fname + '_____________________________________________________________' print movie_2D_shadow.__doc__ quit() if len(varsv.shape) != 3: print errormsg print ' ' + fname + ': wrong variable shadow rank:', varsv.shape, \ 'is has to be 3D!!' quit(-1) # Getting the right lon values for plotting if mapv is not None: dimxv = np.where(dimxv > 180., dimxv-360., dimxv) # Axis ticks # Usually axis > x must be the lon, thus... dimxv0 = dimxv.copy() dimyv0 = dimyv.copy() dxn = dimxv.min() dxx = dimxv.max() dyn = dimyv.min() dyx = dimyv.max() if xaxv[0] == 'pretty': dimxt0 = np.array(gen.pretty_int(dxn,dxx,xaxv[2])) elif xaxv[0] == 'Nfix': dimxt0 = np.arange(dxn,dxx,(dxx-dxn)/(1.*xaxv[2])) elif xaxv[0] == 'Vfix': dimxt0 = np.arange(0,dxx,xaxv[2]) if yaxv[0] == 'pretty': dimyt0 = np.array(gen.pretty_int(dyn,dyx,yaxv[2])) elif yaxv[0] == 'Nfix': dimyt0 = np.arange(dyn,dyx,(dyx-dyn)/(1.*yaxv[2])) elif yaxv[0] == 'Vfix': dimyt0 = np.arange(0,dyx,yaxv[2]) dimxl0 = [] for i in range(len(dimxt0)): dimxl0.append('{:{style}}'.format(dimxt0[i], style=xaxv[1])) dimyl0 = [] for i in range(len(dimyt0)): dimyl0.append('{:{style}}'.format(dimyt0[i], style=yaxv[1])) dimxT0 = variables_values(dimn[0])[0] + ' (' + units_lunits(dimxu) + ')' dimyT0 = variables_values(dimn[1])[0] + ' (' + units_lunits(dimyu) + ')' if mapv is not None: pixkind = 'data' else: # No following data values dimxt0 = np.arange(len(dimxt0),dtype=np.float)/(len(dimxt0)) dimyt0 = np.arange(len(dimyt0),dtype=np.float)/(len(dimyt0)) pixkind = 'fixpixel' if reva is not None: varsv, dimxv, dimyv, dimxt, dimyt, dimxl, dimyl, dimxT, dimyT = \ transform(varsv, reva, dxv=dimxv0, dyv=dimyv0, dxt=dimxt0, dyt=dimyt0, \ dxl=dimxl0, dyl=dimyl0, dxtit=dimxT0, dytit=dimyT0) else: dimxv = dimxv0 dimyv = dimyv0 dimxt = dimxt0 dimyt = dimyt0 dimxl = dimxl0 dimyl = dimyl0 dimxT = dimxT0 dimyT = dimyT0 if len(dimxv[:].shape) == 3: xdims = '1,2' elif len(dimxv[:].shape) == 2: xdims = '0,1' elif len(dimxv[:].shape) == 1: xdims = '0' if len(dimyv[:].shape) == 3: ydims = '1,2' elif len(dimyv[:].shape) == 2: ydims = '0,1' elif len(dimyv[:].shape) == 1: ydims = '0' # lon0 = dimxv # lat0 = dimyv lon0, lat0 = dxdy_lonlat(dimxv,dimyv, xdims, ydims) if not mapv is None: map_proj=mapv.split(',')[0] map_res=mapv.split(',')[1] dx = lon0.shape[1] dy = lat0.shape[0] nlon = np.min(lon0) xlon = np.max(lon0) nlat = np.min(lat0) xlat = np.max(lat0) lon2 = lon0[dy/2,dx/2] lat2 = lat0[dy/2,dx/2] print 'lon2:', lon2, 'lat2:', lat2, 'SW pt:', nlon, ',', nlat, 'NE pt:', \ xlon, ',', xlat if map_proj == 'cyl': m = Basemap(projection=map_proj, llcrnrlon=nlon, llcrnrlat=nlat, \ urcrnrlon=xlon, urcrnrlat= xlat, resolution=map_res) elif map_proj == 'lcc': m = Basemap(projection=map_proj, lat_0=lat2, lon_0=lon2, llcrnrlon=nlon, \ llcrnrlat=nlat, urcrnrlon=xlon, urcrnrlat= xlat, resolution=map_res) else: print errormsg print ' ' + fname + ": map projection '" + map_proj + "' not defined!!!" print ' available: cyl, lcc' quit(-1) x,y = m(lon0,lat0) else: # No following data values x = (dimxv-np.min(dimxv))/(np.max(dimxv) - np.min(dimxv)) y = (dimyv-np.min(dimyv))/(np.max(dimyv) - np.min(dimyv)) # Changing limits of the colors vsend = graphic_range(vs,varsv) # FROM: https://matplotlib.org/examples/animation/moviewriter.html FFMpegWriter = manimation.writers['ffmpeg'] cmt = vnames metadata = dict(title=cmt, artist='Matplotlib', comment='PyNCplot') writer = FFMpegWriter(fps=framesec, metadata=metadata) fig = plt.figure() plt.rc('text', usetex=True) dimt = varsv.shape[dimT] with writer.saving(fig, ofile, dimt): for it in range(dimt): slicev = [] for idn in range(3): if idn == dimT: slicev.append(it) else: slicev.append(slice(0,varsv.shape[idn])) vv = varsv[tuple(slicev)] plt.pcolormesh(x, y, vv, cmap=plt.get_cmap(cbarv[0]), vmin=vsend[0], vmax=vsend[1]) if cbarv[2] == 'horizontal': cbar = plt.colorbar(format=cbarv[1],orientation=cbarv[2]) # From: http://stackoverflow.com/questions/32050030/rotation-of-colorbar-tick-labels-in-matplotlib ticklabels= cbar.ax.get_xticklabels() Nticks = len(ticklabels) ticklabs = [] for itick in range(Nticks): ticklabs.append(ticklabels[itick].get_text()) cbar.ax.set_xticklabels(ticklabs,rotation=90) else: cbar = plt.colorbar(format=cbarv[1],orientation=cbarv[2]) if not mapv is None: if cbarv[0] == 'gist_gray': m.drawcoastlines(color="red") else: m.drawcoastlines() meridians = gen.pretty_int(nlon,xlon,xaxv[2]) m.drawmeridians(meridians,labels=[True,False,False,True]) parallels = gen.pretty_int(nlat,xlat,yaxv[2]) m.drawparallels(parallels,labels=[False,True,True,False]) plt.xlabel('W-E') plt.ylabel('S-N') else: plt.xlabel(dimxT) plt.ylabel(dimyT) plt.axis([x.min(), x.max(), y.min(), y.max()]) if mapv is None: plt.xticks(dimxt, dimxl, rotation=xaxv[3]) plt.yticks(dimyt, dimyl, rotation=yaxv[3]) # units labels cbar.set_label(gen.latex_text(vnames) + ' (' + units_lunits(uts) + ')') graphtit = gen.latex_text(ltit[it]) plt.title(gen.latex_text(graphtit)) #figname = '2D_shadow_frame' + str(it).zfill(int(np.log10(dimt))+1) #output_kind(kfig, figname, True) writer.grab_frame() plt.clf() plt.cla() print fname + ": successful creation of movie '" + ofile + "' !!" return def SaturationPressure(temp): """ Provides de saturation pressure [hPa] at a given temperature following The August-Roche-Magnus equation temp: temperature [K] >>> SaturationPressure(293.15) 23.334406231 """ fname = 'SaturationPressure' ARM1 = 6.1094 # hPa ARM2 = 17.625 # C ARM3 = 243.04 # C tempC = temp - 273.15 satpres = ARM1*exp(ARM2*tempC/(tempC+ARM3)) return satpres #print 'satpres:', SaturationPressure(293.15) def SatMixingRatio(ta,pres): """ Provides de saturation mixing ratio [kgkg-1] ta: temperature [K] pres: pressure [Pa] >>> SatMixingRatio(293.,101300.) 0.014531424608 """ fname = 'SatMixingRatio' es = SaturationPressure(ta) rs = (0.6222*es)/(0.01*pres-es) return rs #print 'saturation mixing ratio:', SatMixingRatio(293.,101300.) def ethetapotct(tsfc, dz=50, pmin=5000.): """ Provides the curve for a given constant equivalent potential temperature starting at surface After: http://www.atmo.arizona.edu/students/courselinks/fall14/atmo551a/Site/ATMO_451a_551a_files/WaterVapor2.pdf https://www.meteo.physik.uni-muenchen.de/~roger/Lectures/Moist%20Convection/Conv_L03_2005.pdf tsfc= temperature at the surface (C) dz= number of points for the curve R = 287.058 (Jkg-1k-1) # 8.3144598 (Jmol-1K-1) Cp = 1.0035 (Jg-1K-1) # 29.07 (Jmol-1K-1) p0 = 100000 # (Pa) psfc = 101325 # (Pa) L = 2264.705 (kJkg-1) """ fname = 'ethetapotct' R = 287.058 # (Jkg1-K-1) Cp = 1003.5 # (Jkg1-K-1) psfc = 101325. # Pa p0 = 100000. # Pa L = 2264.705 # kJkg-1 ethetapotv = np.zeros((dz,2), dtype=np.float) dp = (psfc-pmin)/(dz-1) ws = SatMixingRatio(tsfc+273.15,psfc) thetasfc = (tsfc+273.15)*(psfc/p0)**(R/Cp) for iz in range(dz): ethetapotv[iz,0] = psfc-dp*iz thetapotv = (tsfc+273.15)*((psfc-dp*iz)/p0)**(R/Cp) tfromthetasfc = thetasfc*(p0/(psfc-dp*iz))**(-R/Cp) wstfromthetasfc = SatMixingRatio(tfromthetasfc,psfc-dp*iz) #ethetapotv[iz,1] = thetapotv*np.exp(L*1000.*ws/(Cp*(tsfc+273.15))) -273.15 ethetapotsfcv = thetapotv*np.exp(L*1000.*wstfromthetasfc/(Cp*(tsfc+273.15))) -273.15 ethetapotv[iz,1] = ethetapotsfcv print iz,psfc-dp*iz,thetapotv-273.15,tfromthetasfc-273.15,':',ethetapotv[iz,1],wstfromthetasfc,ethetapotsfcv print thetasfc,ws #quit() return ethetapotv def thetapotct(tsfc, dz=50, pmin=5000.): """ Provides the curve for a given constant potential temperature starting at surface tsfc= temperature at the surface (C) dz= number of points for the curve R = 287.058 (Jkg-1k-1) # 8.3144598 (Jmol-1K-1) Cp = 1.0035 (Jg-1K-1) # 29.07 (Jmol-1K-1) p0 = 100000 # (Pa) psfc = 101325 # (Pa) """ fname = 'thetapotct' R = 287.058 # (Jkg1-K-1) Cp = 1003.5 # (Jkg1-K-1) psfc = 101325. # Pa p0 = 100000. # Pa thetapotv = np.zeros((dz,2), dtype=np.float) dp = (psfc-pmin)/(dz-1) for iz in range(dz): thetapotv[iz,0] = psfc-dp*iz thetapotv[iz,1] = (tsfc+273.15)*((psfc-dp*iz)/p0)**(R/Cp) - 273.15 return thetapotv def plot_SkewT(ta, tda, pres, taxtrm, presxtrm, figtitle, kfig, close): """ Function to plot a SkewT-logP diagram using matplotlib's API example ta: air temperature [C] tda: dew point air temperature [C] pres: pessures for ta and tda [Pa] figtitle: title of figure kfig: kind of graphical output (jpg, pdf, png) close: whether figure should be closed or not """ import skewt fname = 'plot_SkewT' # Checking for variable consistency if len(ta.shape) != 1: print errormsg print ' ' + fname + ": values of 'ta' must have 1D-rank!!" print ' passed shape:', ta.shape quit(-1) if len(tda.shape) != 1: print errormsg print ' ' + fname + ": values of 'tda' must have 1D-rank!!" print ' passed shape:', tda.shape quit(-1) if len(pres.shape) != 1: print errormsg print ' ' + fname + ": values of 'pres' must have 1D-rank!!" print ' passed shape:', pres.shape quit(-1) # Create a new figure. The dimensions here give a good aspect ratio fig = plt.figure(figsize=(6.5875, 6.2125)) ax = fig.add_subplot(111, projection='skewx') plt.grid(True) # Quantity of dryadiabats xmax = taxtrm[1] xmin = taxtrm[0] if len(np.arange(xmin,xmax,10.)) < 10: xfrqtk = 10. else: xfrqtk = 20. # Including dry adiabats ddt = int((xmax+xfrqtk-xmin)/xfrqtk) for itt in range(ddt): dryt = thetapotct(xmin+itt*xfrqtk, pmin=10000.) ax.semilogy(dryt[:,1], dryt[:,0]/100., color='#FFCCCC', linewidth=0.75) # Including moist- adiabats #for itt in range(ddt): # moist = ethetapotct(xmin+itt*xfrqtk, pmin=10000.) # if xmin+itt*xfrqtk == 10.: print moist[:,1], moist[:,0]/100. # ax.semilogy(moist[:,1], moist[:,0]/100., color='#CCFFCC', linewidth=0.75) # Plot the data using normal plotting functions, in this case using # log scaling in Y, as dictated by the typical meteorological plot tamask = ta.mask tdamask = tda.mask ax.semilogy(ta.compressed(), pres[~tamask], color='C3') ax.semilogy(tda.compressed(), pres[~tdamask], color='C2') # An example of a slanted line at constant X l = ax.axvline(0, color='C0') # Disables the log-formatting that comes with semilogy ax.yaxis.set_major_formatter(ScalarFormatter()) ax.yaxis.set_minor_formatter(NullFormatter()) ax.set_yticks(np.linspace(100, 1000, 10)) ax.set_ylim(presxtrm[1], presxtrm[0]) ax.xaxis.set_major_locator(MultipleLocator(10)) ax.set_xlim(taxtrm[0], taxtrm[1]) # Indices #plt.annotate('CAPE: ' + str(stvals['CAPE']), xy=(0.98,0.97), \ # xycoords='axes fraction', ha="right", backgroundcolor='#DDDDDD') #plt.annotate('CI: '+ str(stvals['CI']), xy=(0.98,0.93), xycoords='axes fraction', \ # ha='right', backgroundcolor='#DDDDDD') ax.set_title(gen.latex_text(figtitle)) figname = 'SkewT' output_kind(kfig, figname, close) return def plot_multi_SkewT(tvals, press, taxtrm, presxtrm, kindgS, kindgv, legv, figtitle, kfig, close): """ Function to plot a SkewT-logP diagram with multiple data using matplotlib's API example tvals: dictionary with multiple air temperatures [C] press: dictionary with multiple pessures for ta and tda [Pa] [kindgS]: kind of graphic to produce. To select from: 'multilines': multiple lines [kindgv]: dictionary with values for the given [kindgS] * For 'multilines': 'labels' = list of labels for each line 'collines' = list of colors ('#RRGGBB' values) for each line 'kindmarkers' = list of marker types for each line 'kindlines' = list of line types (matplolib values) of lines 'widthlines' = list of line widths [legv] = [[locleg], [fontsize]] list with the values for the legend [locleg]: location of the legend (0, automatic) 1: 'upper right', 2: 'upper left', 3: 'lower left', 4: 'lower right', 5: 'right', 6: 'center left', 7: 'center right', 8: 'lower center', 9: 'upper center', 10: 'center' [fontsize]: font size for the legend ('auto' for 12) figtitle: title of figure kfig: kind of graphical output (jpg, pdf, png) close: whether figure should be closed or not """ import skewt fname = 'plot_SkewT' # Create a new figure. The dimensions here give a good aspect ratio fig = plt.figure(figsize=(6.5875, 6.2125)) ax = fig.add_subplot(111, projection='skewx') plt.grid(True) # Quantity of dryadiabats xmax = taxtrm[1] xmin = taxtrm[0] if len(np.arange(xmin,xmax,10.)) < 10: xfrqtk = 10. else: xfrqtk = 20. # Including dry adiabats ddt = int((xmax+xfrqtk-xmin)/xfrqtk) for itt in range(ddt): dryt = thetapotct(xmin+itt*xfrqtk, pmin=10000.) ax.semilogy(dryt[:,1], dryt[:,0]/100., color='#FFCCCC', linewidth=0.75) # Including moist- adiabats (not working yet) #for itt in range(ddt): # moist = ethetapotct(xmin+itt*xfrqtk, pmin=10000.) # if xmin+itt*xfrqtk == 10.: print moist[:,1], moist[:,0]/100. # ax.semilogy(moist[:,1], moist[:,0]/100., color='#CCFFCC', linewidth=0.75) # An example of a slanted line at constant X l = ax.axvline(0, color='C0') Nlines = len(tvals) NLlines = len(kindgv['labels']) if Nlines != NLlines: print errormsg print ' ' + fname + ': number of lines:', Nlines, \ ' and number of labels:', NLlines, 'do not coincide !!' print ' provided labels:', kindgv['labels'] quit(-1) print ' ' + fname + ': plotting ', Nlines, 'lines ...' for iline in range(Nlines): ta = tvals[iline] pres = press[iline] # line characteristics lline = kindgv['labels'][iline] cline = kindgv['collines'][iline] kmark = kindgv['kindmarkers'][iline] kline = kindgv['kindlines'][iline] wline = np.float(kindgv['widthlines'][iline]) # Checking for variable consistency if len(ta.shape) != 1: print errormsg print ' ' + fname + ": values of 'T[" + str(iline) + "]' must have " + \ "1D-rank!!" print ' passed shape:', ta.shape quit(-1) if len(pres.shape) != 1: print errormsg print ' ' +fname+ ": values of 'pres[" + str(iline) + "]' must have " + \ "1D-rank!!" print ' passed shape:', pres.shape quit(-1) # Plot the data using normal plotting functions, in this case using # log scaling in Y, as dictated by the typical meteorological plot tamask = ta.mask if len(tamask.shape) == 0: print ' ' + fname + ': values without any masked value!' tamask = np.ones((ta.shape), dtype=bool)*tamask if lline != 'None': ax.semilogy(ta.compressed(), pres[~tamask], kline, color=cline, \ linewidth=wline, marker=kmark, label=lline) else: ax.semilogy(ta.compressed(), pres[~tamask], kline, color=cline, \ linewidth=wline, marker=kmark) # Disables the log-formatting that comes with semilogy ax.yaxis.set_major_formatter(ScalarFormatter()) ax.yaxis.set_minor_formatter(NullFormatter()) ax.set_yticks(np.linspace(100, 1000, 10)) ax.set_ylim(presxtrm[1], presxtrm[0]) ax.xaxis.set_major_locator(MultipleLocator(10)) ax.set_xlim(taxtrm[0], taxtrm[1]) # Indices #plt.annotate('CAPE: ' + str(stvals['CAPE']), xy=(0.98,0.97), \ # xycoords='axes fraction', ha="right", backgroundcolor='#DDDDDD') #plt.annotate('CI: '+ str(stvals['CI']), xy=(0.98,0.93), xycoords='axes fraction', \ # ha='right', backgroundcolor='#DDDDDD') plt.legend(loc=legv[0], prop={'size':legv[1]}) ax.set_xlabel('t ($^{\circ}$C)') ax.set_ylabel('pres (hPa)') ax.set_title(gen.latex_text(figtitle)) figname = 'multi_SkewT' output_kind(kfig, figname, close) return def plot_2Dshad_obssim(obsv, varsv, dimxv, dimyv, reva, diminf, xaxv, yaxv, cbarv, \ vs, varinf, discinf, mapv, gmaxmin, figtitle, kfig, close): """ Function to plot a 2D shadding plot with comparison between observations (as filled colored circles) and simulation (shadded continuous field) obsv= 3-column with observational values (x, y, value) varsv= 2D matrix of simulation values dimxv= values for x-coordinate from simulation dimyv= values for y-coordinate from simulation reva= in case of modification of the plotting of 2D variables ('|' can be used for combination) * 'transpose': reverse the axes (x-->y, y-->x) * 'flip'@[x/y]: flip the axis x or y diminf= dictionary with the information from the dimensions in the plot diminf['units']= [dimxu, dimyu]: units at the axes of x and y diminf['names']= [dimxn, dimyn]: names of the dimension xaxv= list with the x-axis paramteres [style, format, number and orientation] yaxv= list with the y-axis paramteres [style, format, number and orientation] cbarv= list with the parameters of the color bar [colorbar, cbarfmt, cbaror] colorbar: name of the color bar to use cbarfmt: format of the numbers in the colorbar cbaror: orientation of the colorbar vs= list with minmum and maximum values to plot in shadow or one strings forminimum and maximum for: 'Srange': for full range 'Saroundmean@val': for mean-xtrm,mean+xtrm where xtrm = np.min(mean-min@val,max@val-mean) 'Saroundminmax@val': for min*val,max*val 'Saroundpercentile@val': for median-xtrm,median+xtrm where xtrm = np.min(median-percentile_(val), percentile_(100-val)-median) 'Smean@val': for -xtrm,xtrm where xtrm = np.min(mean-min*@val,max*@val-mean) 'Smedian@val': for -xtrm,xtrm where xtrm = np.min(median-min@val,max@val-median) 'Spercentile@val': for -xtrm,xtrm where xtrm = np.min(median-percentile_(val), percentile_(100-val)-median) varinf= dictionary with the information of the variable in the plot varinf['units']= units of the variable to shadow varinf['name']= name of the variable discinf= [[type],[size],[lwidth],[lcol]] characteristics of the points for the discrete field [type]: type of point. Any from matoplib must be filled ! [size]: size of point [lwidht]: width of the line around the marker [lcol]: color of the line around the marker mapv= map characteristics: [proj],[res] see full documentation: http://matplotlib.org/basemap/ [proj]: projection * 'cyl', cilindric * 'lcc', lambert conformal [res]: resolution: * 'c', crude * 'l', low * 'i', intermediate * 'h', high * 'f', full gmaxmin= [xaxismin, xaxismax, yaxismin, yaxismax] minimum and maximum values of the axis of the figure figtitle= title of the figure kifg= kind of figure file output (png, ps, pdf) close= whether figure should be closed or not """ fname = 'plot_2Dshad_obssim' if len(varsv.shape) != 2: print errormsg print ' ' + fname + ': wrong variable shadow rank:', varsv.shape, \ 'is has to be 2D!!' quit(-1) # Getting the right lon values for plotting if mapv is not None: dimxv = np.where(dimxv > 180., dimxv-360., dimxv) # Axis ticks # Usually axis > x must be the lon, thus... dimxv0 = dimxv.copy() dimyv0 = dimyv.copy() dxn = dimxv.min() dxx = dimxv.max() dyn = dimyv.min() dyx = dimyv.max() if xaxv[0] == 'pretty': dimxt0 = np.array(gen.pretty_int(dxn,dxx,xaxv[2])) elif xaxv[0] == 'Nfix': dimxt0 = np.arange(dxn,dxx,(dxx-dxn)/(1.*xaxv[2])) elif xaxv[0] == 'Vfix': dimxt0 = np.arange(xaxv[2]*int(dxn/xaxv[2]),dxx+xaxv[2],xaxv[2]) if yaxv[0] == 'pretty': dimyt0 = np.array(gen.pretty_int(dyn,dyx,yaxv[2])) elif yaxv[0] == 'Nfix': dimyt0 = np.arange(dyn,dyx,(dyx-dyn)/(1.*yaxv[2])) elif yaxv[0] == 'Vfix': dimyt0 = np.arange(yaxv[2]*int(dyn/yaxv[2]),dyx+yaxv[2],yaxv[2]) dimxl0 = [] for i in range(len(dimxt0)): dimxl0.append('{:{style}}'.format(dimxt0[i], style=xaxv[1])) dimyl0 = [] for i in range(len(dimyt0)): dimyl0.append('{:{style}}'.format(dimyt0[i], style=yaxv[1])) dimn = diminf['names'] dimxu = diminf['units'][0] dimyu = diminf['units'][1] dimxT0 = variables_values(dimn[0])[0] + ' (' + units_lunits(dimxu) + ')' dimyT0 = variables_values(dimn[1])[0] + ' (' + units_lunits(dimyu) + ')' pixkind = 'data' if reva is not None: varsv, dimxv, dimyv, dimxt, dimyt, dimxl, dimyl, dimxT, dimyT, limx, limy = \ gen.transform(varsv, reva, dxv=dimxv0, dyv=dimyv0, dxt=dimxt0, dyt=dimyt0, \ dxl=dimxl0, dyl=dimyl0, dxtit=dimxT0, dytit=dimyT0) else: dimxv = dimxv0 dimyv = dimyv0 dimxt = dimxt0 dimyt = dimyt0 dimxl = dimxl0 dimyl = dimyl0 dimxT = dimxT0 dimyT = dimyT0 limx = [dxn, dxx] limy = [dyn, dyx] if not mapv is None: map_proj=mapv.split(',')[0] map_res=mapv.split(',')[1] lon0 = dimxv.copy() lat0 = dimyv.copy() dx = lon0.shape[1] dy = lat0.shape[0] #nlon = np.min(lon0) #xlon = np.max(lon0) #nlat = np.min(lat0) #xlat = np.max(lat0) nlon = gmaxmin[0] xlon = gmaxmin[1] nlat = gmaxmin[2] xlat = gmaxmin[3] lon2 = lon0[dy/2,dx/2] lat2 = lat0[dy/2,dx/2] print 'lon2:', lon2, 'lat2:', lat2, 'SW pt:', nlon, ',', nlat, 'NE pt:', \ xlon, ',', xlat if map_proj == 'cyl': m = Basemap(projection=map_proj, llcrnrlon=nlon, llcrnrlat=nlat, \ urcrnrlon=xlon, urcrnrlat= xlat, resolution=map_res) elif map_proj == 'lcc': m = Basemap(projection=map_proj, lat_0=lat2, lon_0=lon2, llcrnrlon=nlon, \ llcrnrlat=nlat, urcrnrlon=xlon, urcrnrlat= xlat, resolution=map_res) else: print errormsg print ' ' + fname + ": map projection '" + map_proj + "' not defined!!!" print ' available: cyl, lcc' quit(-1) x,y = m(lon0,lat0) else: # No following data values x = (dimxv-np.min(dimxv))/(np.max(dimxv) - np.min(dimxv)) y = (dimyv-np.min(dimyv))/(np.max(dimyv) - np.min(dimyv)) # Changing limits of the colors # Combining values fvarsv = varsv.flatten() fobsv = obsv[:,2].flatten() # Getting extremes only from the plotted area stmapvals, ijmapvals = ncvar.stats_lonlat_box(varsv, lon0, lat0, nlon, xlon, nlat, xlat) allvals = np.array(stmapvals[0:2] + list(fobsv)) #print ' Figure minmax:', stmapvals[0:2], 'absolute:', np.min(varsv), np.max(varsv) vsend = graphic_range(vs, allvals) plt.rc('text',usetex=True) # 2D continuous shaded field plt.pcolormesh(x, y, varsv, cmap=plt.get_cmap(cbarv[0]), vmin=vsend[0], vmax=vsend[1]) # in case using scatter #cbar = plt.colorbar(format=cbarv[1],orientation=cbarv[2]) # Adding observations Nobs = obsv.shape[0] # Normalize into x,y space if mapv is None: xmin = np.min(dimxv) xmax = np.max(dimxv) ymin = np.min(dimyv) ymax = np.max(dimyv) else: xmin = np.min(lon0) xmax = np.max(lon0) ymin = np.min(lat0) ymax = np.max(lat0) # Normalize colors my_cmap = plt.cm.get_cmap(cbarv[0]) norm = mpl.colors.Normalize(vsend[0],vsend[1]) for iobs in range(Nobs): if mapv is None: xobs = (obsv[iobs,0]-xmin)/(xmax-xmin) yobs = (obsv[iobs,1]-ymin)/(ymax-ymin) else: xobs = obsv[iobs,0] yobs = obsv[iobs,1] clv = my_cmap(norm(obsv[iobs,2])) plt.plot(xobs, yobs, discinf[0], color=clv, markersize=discinf[1], zorder=100) plt.plot(xobs, yobs, discinf[0], color=discinf[3], linewidth=discinf[2], \ markersize=discinf[1], zorder=100, fillstyle='none') # with scatter... same result! #xobs = (obsv[:,0]-xmin)/(xmax-xmin) #yobs = (obsv[:,1]-ymin)/(ymax-ymin) #clv = my_cmap(norm(obsv[:,2])) #plt.scatter(xobs, yobs, s=discinf[1]*10., c=clv, zorder=100) if cbarv[2] == 'horizontal': cbar = plt.colorbar(format=cbarv[1],orientation=cbarv[2]) # From: http://stackoverflow.com/questions/32050030/rotation-of-colorbar-tick-labels-in-matplotlib ticklabels= cbar.ax.get_xticklabels() Nticks = len(ticklabels) ticklabs = [] for itick in range(Nticks): ticklabs.append(ticklabels[itick].get_text()) cbar.ax.set_xticklabels(ticklabs,rotation=90) else: cbar = plt.colorbar(format=cbarv[1],orientation=cbarv[2]) if not mapv is None: if cbarv[0] == 'gist_gray': m.drawcoastlines(color="red") else: m.drawcoastlines() meridians = gen.pretty_int(nlon,xlon,xaxv[2]) m.drawmeridians(meridians,labels=[True,False,False,True]) parallels = gen.pretty_int(nlat,xlat,yaxv[2]) m.drawparallels(parallels,labels=[False,True,True,False]) plt.xlabel('W-E') plt.ylabel('S-N') else: plt.xlabel(dimxT) plt.ylabel(dimyT) if mapv is None: ldimxt = list(dimxt) ldimyt = list(dimyt) for val in ldimxt: if val < np.min(limx): ldimxt.remove(val) if val > np.max(limx): ldimxt.remove(val) for val in ldimyt: if val < np.min(limy): ldimyt.remove(val) if val > np.max(limy): ldimyt.remove(val) dimxt = np.array(ldimxt) dimyt = np.array(ldimyt) dxt = gen.interpolate_locs(dimxt,dimxv[0,:],'lin') dyt = gen.interpolate_locs(dimyt,dimyv[:,0],'lin') dimxt = dxt/varsv.shape[1] dimyt = dyt/varsv.shape[0] # Using output from transform gxn = (gmaxmin[0]-xmin)/(xmax-xmin) gxx = (gmaxmin[1]-xmin)/(xmax-xmin) gyn = (gmaxmin[2]-ymin)/(ymax-ymin) gyx = (gmaxmin[3]-ymin)/(ymax-ymin) #gxn = (limx[0]-xmin)/(xmax-xmin) #gxx = (limx[1]-xmin)/(xmax-xmin) #gyn = (limy[0]-ymin)/(ymax-ymin) #gyx = (limy[1]-ymin)/(ymax-ymin) # Are axis flipped? signxl = np.abs(limx[0]-limx[1])/(limx[0]-limx[1]) signxt = np.abs(ldimxt[0]-ldimxt[1])/(ldimxt[0]-ldimxt[1]) signyl = np.abs(limy[0]-limy[1])/(limy[0]-limy[1]) signyt = np.abs(ldimyt[0]-ldimyt[1])/(ldimyt[0]-ldimyt[1]) if signxl != signxt: plt.xticks(1.-dimxt, dimxl, rotation=xaxv[3]) else: plt.xticks(dimxt, dimxl, rotation=xaxv[3]) if signyl != signyt: plt.yticks(1.-dimyt, dimyl, rotation=yaxv[3]) else: plt.yticks(dimyt, dimyl, rotation=yaxv[3]) # Only if gmaxmin is used to compute limits of the figure !! if signxl != signxt: newgxn = gxx newgxx = gxn else: newgxn = gxn newgxx = gxx if signyl != signyt: newgyn = gyx newgyx = gyn else: newgyn = gyn newgyx = gyx plt.axis([newgxn, newgxx, newgyn, newgyx]) # otherwise #plt.axis([gxn, gxx, gyn, gyx]) # units labels cbar.set_label(gen.latex_text(varinf['name']) + ' (' + \ units_lunits(varinf['units']) + ')') plt.title(gen.latex_text(figtitle)) figname = '2Dshad_obs-sim_comparison' output_kind(kfig, figname, close) return def plot_2Dshad_obssim_time(obsv, varsv, dimtv, dimvv, dataxis, reva, diminf, vaxv, \ timeinf, cbarv, vs, varinf, discinf, mapv, gmaxmin, figtitle, kfig, close): """ Function to plot a 2D shadding plot with comparison between observations (as filled colored circles) and simulation (shadded continuous field) with a time-axis obsv= 3-column with observational values (x, y, value) varsv= 2D matrix of simulation values dimtv= values for t-coordinate from simulation dimvv= values for v-coordinate from simulation dataxis= which axis 'x' or 'y' should be use for the non-temporal dimension reva= in case of modification of the plotting of 2D variables ('|' can be used for combination) * 'transpose': reverse the axes (x-->y, y-->x) * 'flip'@[x/y]: flip the axis x or y diminf= dictionary with the information from the dimensions in the plot diminf['units']= [dimxu, dimyu]: units at the axes of x and y diminf['names']= [dimxn, dimyn]: names of the dimension vaxv= list with the v-axis paramteres [style, format, number and orientation] timeinf= dictionary with information for the time-axis 'tpos': positions of the markers 'tlabs': labels of the markers 'name': name in graphic 'units': units cbarv= list with the parameters of the color bar [colorbar, cbarfmt, cbaror] colorbar: name of the color bar to use cbarfmt: format of the numbers in the colorbar cbaror: orientation of the colorbar vs= list with minmum and maximum values to plot in shadow or one strings forminimum and maximum for: 'Srange': for full range 'Saroundmean@val': for mean-xtrm,mean+xtrm where xtrm = np.min(mean-min@val,max@val-mean) 'Saroundminmax@val': for min*val,max*val 'Saroundpercentile@val': for median-xtrm,median+xtrm where xtrm = np.min(median-percentile_(val), percentile_(100-val)-median) 'Smean@val': for -xtrm,xtrm where xtrm = np.min(mean-min*@val,max*@val-mean) 'Smedian@val': for -xtrm,xtrm where xtrm = np.min(median-min@val,max@val-median) 'Spercentile@val': for -xtrm,xtrm where xtrm = np.min(median-percentile_(val), percentile_(100-val)-median) varinf= dictionary with the information of the variable in the plot varinf['units']= units of the variable to shadow varinf['name']= name of the variable discinf= [[type],[size],[lwidth],[lcol]] characteristics of the points for the discrete field [type]: type of point. Any from matoplib must be filled ! [size]: size of point [lwidht]: width of the line around the marker [lcol]: color of the line around the marker mapv= map characteristics: [proj],[res] see full documentation: http://matplotlib.org/basemap/ [proj]: projection * 'cyl', cilindric * 'lcc', lambert conformal [res]: resolution: * 'c', crude * 'l', low * 'i', intermediate * 'h', high * 'f', full gmaxmin= [xaxismin, xaxismax, yaxismin, yaxismax] minimum and maximum values of the axis of the figure figtitle= title of the figure kifg= kind of figure file output (png, ps, pdf) close= whether figure should be closed or not """ fname = 'plot_2Dshad_obssim' if len(varsv.shape) != 2: print errormsg print ' ' + fname + ': wrong variable shadow rank:', varsv.shape, \ 'is has to be 2D!!' quit(-1) # Getting the right lon values for plotting if mapv is not None: dimxv = np.where(dimxv > 180., dimxv-360., dimxv) # Axis ticks # Usually axis > x must be the time, thus... dimxv0 = dimtv.copy() dimyv0 = dimvv.copy() dxn = dimtv.min() dxx = dimtv.max() dyn = dimvv.min() dyx = dimvv.max() dimxt0 = timeinf['tpos'] dimxl0 = timeinf['tlabs'] if vaxv[0] == 'pretty': dimyt0 = np.array(gen.pretty_int(dyn,dyx,vaxv[2])) elif vaxv[0] == 'Nfix': dimyt0 = np.arange(dyn,dyx,(dyx-dyn)/(1.*vaxv[2])) elif vaxv[0] == 'Vfix': dimyt0 = np.arange(vaxv[2]*int(dyn/vaxv[2]),dyx+vaxv[2],vaxv[2]) dimyl0 = [] for i in range(len(dimyt0)): dimyl0.append('{:{style}}'.format(dimyt0[i], \ style=vaxv[1])) dimn = diminf['names'] dimyu = diminf['units'][1] dimxT0 = timeinf['name'] dimyT0 = variables_values(dimn[1])[0] + ' (' + units_lunits(dimyu) + ')' pixkind = 'data' if dataxis == 'x': if reva is not None: reva = 'transpose|' + reva else: reva = 'transpose' if reva is not None: varsv, dimxv, dimyv, dimxt, dimyt, dimxl, dimyl, dimxT, dimyT, limx, limy = \ gen.transform(varsv, reva, dxv=dimxv0, dyv=dimyv0, dxt=dimxt0, dyt=dimyt0, \ dxl=dimxl0, dyl=dimyl0, dxtit=dimxT0, dytit=dimyT0) else: dimxv = dimxv0 dimyv = dimyv0 dimxt = dimxt0 dimyt = dimyt0 dimxl = dimxl0 dimyl = dimyl0 dimxT = dimxT0 dimyT = dimyT0 limx = [dxn, dxx] limy = [dyn, dyx] if not mapv is None: map_proj=mapv.split(',')[0] map_res=mapv.split(',')[1] lon0 = dimxv.copy() lat0 = dimyv.copy() dx = lon0.shape[1] dy = lat0.shape[0] nlon = np.min(lon0) xlon = np.max(lon0) nlat = np.min(lat0) xlat = np.max(lat0) lon2 = lon0[dy/2,dx/2] lat2 = lat0[dy/2,dx/2] print 'lon2:', lon2, 'lat2:', lat2, 'SW pt:', nlon, ',', nlat, 'NE pt:', \ xlon, ',', xlat if map_proj == 'cyl': m = Basemap(projection=map_proj, llcrnrlon=nlon, llcrnrlat=nlat, \ urcrnrlon=xlon, urcrnrlat= xlat, resolution=map_res) elif map_proj == 'lcc': m = Basemap(projection=map_proj, lat_0=lat2, lon_0=lon2, llcrnrlon=nlon, \ llcrnrlat=nlat, urcrnrlon=xlon, urcrnrlat= xlat, resolution=map_res) else: print errormsg print ' ' + fname + ": map projection '" + map_proj + "' not defined!!!" print ' available: cyl, lcc' quit(-1) x,y = m(lon0,lat0) else: # No following data values x = (dimxv-np.min(dimxv))/(np.max(dimxv) - np.min(dimxv)) y = (dimyv-np.min(dimyv))/(np.max(dimyv) - np.min(dimyv)) # Changing limits of the colors # Combining values fvarsv = varsv.flatten() fobsv = obsv[:,2].flatten() allvals = np.array(list(fvarsv) + list(fobsv)) vsend = graphic_range(vs, allvals) plt.rc('text',usetex=True) # 2D continuous shaded field plt.pcolormesh(x, y, varsv, cmap=plt.get_cmap(cbarv[0]), vmin=vsend[0], vmax=vsend[1]) # in case using scatter #cbar = plt.colorbar(format=cbarv[1],orientation=cbarv[2]) # Adding observations Nobs = obsv.shape[0] # Normalize into x,y space if mapv is None: xmin = np.min(dimxv) xmax = np.max(dimxv) ymin = np.min(dimyv) ymax = np.max(dimyv) else: xmin = np.min(lon0) xmax = np.max(lon0) ymin = np.min(lat0) ymax = np.max(lat0) # Normalize colors my_cmap = plt.cm.get_cmap(cbarv[0]) norm = mpl.colors.Normalize(vsend[0],vsend[1]) for iobs in range(Nobs): xobs = (obsv[iobs,0]-xmin)/(xmax-xmin) yobs = (obsv[iobs,1]-ymin)/(ymax-ymin) clv = my_cmap(norm(obsv[iobs,2])) plt.plot(xobs, yobs, discinf[0], color=clv, markersize=discinf[1], zorder=100) plt.plot(xobs, yobs, discinf[0], color=discinf[3], linewidth=discinf[2], \ markersize=discinf[1], zorder=100, fillstyle='none') # with scatter... same result! #xobs = (obsv[:,0]-xmin)/(xmax-xmin) #yobs = (obsv[:,1]-ymin)/(ymax-ymin) #clv = my_cmap(norm(obsv[:,2])) #plt.scatter(xobs, yobs, s=discinf[1]*10., c=clv, zorder=100) if cbarv[2] == 'horizontal': cbar = plt.colorbar(format=cbarv[1],orientation=cbarv[2]) # From: http://stackoverflow.com/questions/32050030/rotation-of-colorbar-tick-labels-in-matplotlib ticklabels= cbar.ax.get_xticklabels() Nticks = len(ticklabels) ticklabs = [] for itick in range(Nticks): ticklabs.append(ticklabels[itick].get_text()) cbar.ax.set_xticklabels(ticklabs,rotation=90) else: cbar = plt.colorbar(format=cbarv[1],orientation=cbarv[2]) if not mapv is None: if cbarv[0] == 'gist_gray': m.drawcoastlines(color="red") else: m.drawcoastlines() meridians = gen.pretty_int(nlon,xlon,xaxv[2]) m.drawmeridians(meridians,labels=[True,False,False,True]) parallels = gen.pretty_int(nlat,xlat,yaxv[2]) m.drawparallels(parallels,labels=[False,True,True,False]) plt.xlabel('W-E') plt.ylabel('S-N') else: plt.xlabel(dimxT) plt.ylabel(dimyT) if mapv is None: ldimxt = list(dimxt) ldimyt = list(dimyt) for val in ldimxt: if val < np.min(limx): ldimxt.remove(val) if val > np.max(limx): ldimxt.remove(val) for val in ldimyt: if val < np.min(limy): ldimyt.remove(val) if val > np.max(limy): ldimyt.remove(val) dimxt = np.array(ldimxt) dimyt = np.array(ldimyt) dxt = gen.interpolate_locs(dimxt,dimxv[0,:],'lin') dyt = gen.interpolate_locs(dimyt,dimyv[:,0],'lin') dimxt = dxt/varsv.shape[1] dimyt = dyt/varsv.shape[0] # Using output from transform gxn = (gmaxmin[0]-xmin)/(xmax-xmin) gxx = (gmaxmin[1]-xmin)/(xmax-xmin) gyn = (gmaxmin[2]-ymin)/(ymax-ymin) gyx = (gmaxmin[3]-ymin)/(ymax-ymin) #gxn = (limx[0]-xmin)/(xmax-xmin) #gxx = (limx[1]-xmin)/(xmax-xmin) #gyn = (limy[0]-ymin)/(ymax-ymin) #gyx = (limy[1]-ymin)/(ymax-ymin) # Are axis flipped? signxl = np.abs(limx[0]-limx[1])/(limx[0]-limx[1]) signxt = np.abs(ldimxt[0]-ldimxt[1])/(ldimxt[0]-ldimxt[1]) signyl = np.abs(limy[0]-limy[1])/(limy[0]-limy[1]) signyt = np.abs(ldimyt[0]-ldimyt[1])/(ldimyt[0]-ldimyt[1]) if signxl != signxt: plt.xticks(1.-dimxt, dimxl) else: plt.xticks(dimxt, dimxl) if signyl != signyt: plt.yticks(1.-dimyt, dimyl, rotation=vaxv[3]) else: plt.yticks(dimyt, dimyl, rotation=vaxv[3]) # Only if gmaxmin is used to compute limits of the figure !! if signxl != signxt: newgxn = gxx newgxx = gxn else: newgxn = gxn newgxx = gxx if signyl != signyt: newgyn = gyx newgyx = gyn else: newgyn = gyn newgyx = gyx plt.axis([newgxn, newgxx, newgyn, newgyx]) # otherwise #plt.axis([gxn, gxx, gyn, gyx]) # units labels cbar.set_label(gen.latex_text(varinf['name']) + ' (' + \ units_lunits(varinf['units']) + ')') plt.title(gen.latex_text(figtitle)) figname = '2Dshad_obs-sim_comparison_time' output_kind(kfig, figname, close) return