source: BOL/Multi_atlas/AXE4/make_axe4-temp-DC-mast.py @ 5215

Last change on this file since 5215 was 4700, checked in by musat, 14 months ago

Adaptation scripts AXE4 a spirit2
IonelaMusat?

  • Property svn:executable set to *
File size: 6.2 KB
Line 
1#! /usr/bin/env python
2# JBM
3# 24/11/2016: Corrected altitude
4# 09/01/2017: Improved initialization of time axis
5from netCDF4 import Dataset as NetCDFFile
6from netCDF4 import num2date
7import numpy as np
8import matplotlib.pyplot as plt
9import matplotlib.dates as dates
10import datetime
11from matplotlib.dates import date2num
12import pandas
13from optparse import OptionParser
14from pylab import savefig
15import sys, getopt
16
17def main(argv):
18  inputfile = ''
19  outputdir = ''
20  errmsg='Use: '+str(sys.argv[0])+' -i <inputfile> -o <outputdir>'
21  try:
22     opts, args = getopt.getopt(argv,"h:i:o:")
23  except getopt.GetoptError:
24     print(errmsg)
25     sys.exit(2)
26  for opt, arg in opts:
27     if opt == '-h':
28        print(errmsg)
29        sys.exit()
30     elif opt in ("-i"):
31        inputfile = arg
32     elif opt in ("-o"):
33        outputdir = arg
34  if len(inputfile) == 0 or len(outputdir) == 0:
35    print('Please specify an input file and an output directory.')
36    print(errmsg)
37    sys.exit()
38  print( 'Input file is ', inputfile)
39  print('Output directory is ', outputdir)
40
41  # MAIN PROGRAM
42  # -----------------------------------------------------------------
43
44  ncfile=inputfile
45  if len(ncfile.rsplit('/',1)) > 1:
46    decomp=(ncfile.rsplit('/',1))[1].rsplit('_',5)
47  else:
48    decomp=ncfile.rsplit('_',5)
49  short=decomp[0]+'_'+decomp[2]+'_'+decomp[3]
50#  shortname=short.replace(".","-")
51  shortname=short
52
53  datapath='/thredds/ipsl/fabric/lmdz/AXE4/'
54
55  # LOADING THE DATA
56  # -----------------------------------------------------------------
57 
58  # Read the files using the (very convenient) Pandas reader
59  #data = pandas.read_csv('CR3000_Tour_PT100_30_Air_T.dat',sep=',', na_values=".")
60  #data = pandas.read_csv('CR3000_Tour_PT100_30.dat',sep=',', na_values=".")
61  #data = pandas.read_csv('temp10+_modified.dat',parse_dates='Date',sep=';', na_values=".")
62  data = pandas.read_csv(datapath+'/'+'temp10+_modified.dat',sep=';', na_values=".")
63 
64  # Monthly mean
65  # ------------
66 
67  data.index = pandas.to_datetime(data['Date'], format='%Y-%m-%d %H:%M:%S')
68  #IMorig datamth=data.resample('M', how='mean')
69  datamth=data.resample('M').mean()
70  levels_obs = [3.5, 10.9, 18.3, 25.6, 33., 42.2]
71 
72  # Full dataset
73  # ------------
74 
75  print(data.columns)
76 
77  # LOADING THE GCM RESULTS
78  # -----------------------------------------------------------------
79 
80  # FILE 1
81  nc = NetCDFFile(ncfile)
82  time = nc.variables['time_counter'][:]
83  temp = nc.variables['temp'][:]
84  longi = nc.variables['lon'][:]
85  lati = nc.variables['lat'][:]
86  longi_user = 123.
87  longi_id = np.abs(longi - longi_user).argmin()
88  lati_user = -75.
89  lati_id = np.abs(lati - lati_user).argmin()
90  alti_id = range(4)
91  alti_var = np.zeros(4)
92  flabel = ['']*4
93  if str(nc.variables).find("geop") > -1 and \
94     str(nc.variables).find("phis") > -1:
95    geop = nc.variables['geop'][:]
96    phis = nc.variables['phis'][:]
97    for ilev in range(4):
98      alti_var[ilev] = np.mean(geop[:,alti_id[ilev],lati_id,longi_id] - \
99                       phis[:,lati_id,longi_id])/9.8
100      flabel[ilev] = \
101        "LMDz (z="+str("%.1f" % alti_var[ilev])+"m)"
102  else:
103    flabel[0] = "LMDz (z=6m approx.)"
104    flabel[1] = "LMDz (z=20m approx.)"
105    flabel[2] = "LMDz (z=35m approx.)"
106    flabel[3] = "LMDz (z=53m approx.)"
107  print(longi[longi_id])
108  print(lati[lati_id])
109
110  if time[0] > 86400:
111  # Time axis is in seconds
112    date = num2date(time[:], units = 'seconds since 2010-01-01 00:00:00')
113  elif time[0] > 1:
114  # Time axis is in days
115    date = num2date(time[:], units = 'days since 2010-01-01 00:00:00')
116  else:
117  # Time axis is in months
118    date = num2date(time[:], units = 'months since 2010-01-01 00:00:00')
119
120  # DISPLAYING THE RESULTS
121  # -----------------------------------------------------------------
122  # We plot the figure
123  fig = plt.figure()
124  ax = fig.gca()
125  ax.set_xticks(date)
126  ax.set_xticklabels(date)
127  ax.xaxis.set_major_locator(dates.MonthLocator())
128  ax.xaxis.set_major_formatter(dates.DateFormatter('%b'))
129  ax.set_title(shortname)
130  ax.set_ylabel("Air temperature (degC)")
131  plt.grid()
132 
133  #plt.plot(codedate, uservar1) # DATA
134  #plt.plot(codedate, uservar1,'0.8') # FULL full
135  linegcm=plt.plot(date,temp[:,alti_id[0],lati_id,longi_id]-273.15,'k-o',linewidth=2,label=flabel[0]) # GCM
136  lineobs=plt.plot(date,datamth['tm1'],'k--', \
137    linewidth=2,label='OBS '+str("%.1f" % levels_obs[0])+'m (2010)') # DATA monthly mean
138  lineobs=plt.plot(date,datamth['tm2'],'k--', \
139    linewidth=2,label='OBS '+str("%.1f" % levels_obs[1])+'m (2010)') # DATA monthly mean
140  linegcm=plt.plot(date,temp[:,alti_id[1],lati_id,longi_id]-273.15,'b-o',linewidth=2,label=flabel[1]) # GCM
141  lineobs=plt.plot(date,datamth['tm3'],'b--', \
142    linewidth=2,label='OBS '+str("%.1f" % levels_obs[2])+'m (2010)') # DATA monthly mean
143  lineobs=plt.plot(date,datamth['tm4'],'b--', \
144    linewidth=2,label='OBS '+str("%.1f" % levels_obs[3])+'m (2010)') # DATA monthly mean
145  linegcm=plt.plot(date,temp[:,alti_id[2],lati_id,longi_id]-273.15,'r-o',linewidth=2,label=flabel[2]) # GCM
146  lineobs=plt.plot(date,datamth['tm5'],'r--', \
147    linewidth=2,label='OBS '+str("%.1f" % levels_obs[4])+'m (2010)') # DATA monthly mean
148  lineobs=plt.plot(date,datamth['tm6'],'r--', \
149    linewidth=2,label='OBS '+str("%.1f" % levels_obs[5])+'m (2010)') # DATA monthly mean
150#  linegcm=plt.plot(date,temp[:,alti_id[3],lati_id,longi_id]-273.15,'g-o',linewidth=2,label=flabel[3]) # GCM
151  #linegcm=plt.plot(date, temp2[:,alti_id,lati_id,longi_id]-273.15,'b-o',linewidth=2,label='NPv5.5 (1982-1989)') # GCM
152  #plt.plot(date, t2m[:,lati_id,longi_id]-273.15,'ro') # GCM
153 
154  handles=[lineobs, linegcm]
155  ax.legend(handles)
156  plt.legend(loc=(1.03, 0.8))
157  #plt.legend(('pvap (bottom)', 'pvap (top)'), loc=(1.03, 0.8))
158  plt.xticks(rotation=30,ha='right') #plt.xticks(rotation='vertical')
159  plt.subplots_adjust(bottom=0.2)
160  plt.subplots_adjust(right=0.65) # keep room for legend e.g. 0.8
161 
162  savefig(outputdir+'/'+'tempDC-'+shortname+'.png', bbox_inches='tight')
163  #plt.show()
164
165  # -----------------------------------------------------------------
166  # -----------------------------------------------------------------
167  # -----------------------------------------------------------------
168
169# MAIN PROGRAM
170# Just calling the main function
171if __name__ == "__main__":
172   main(sys.argv[1:])
173
174#------------------------------------------------------------------
175
176
Note: See TracBrowser for help on using the repository browser.