Changeset 349 for trunk/MESOSCALE/LMD_MM_MARS
- Timestamp:
- Nov 5, 2011, 6:54:37 PM (13 years ago)
- Location:
- trunk/MESOSCALE/LMD_MM_MARS/SRC/PYTHON
- Files:
-
- 3 added
- 4 edited
Legend:
- Unmodified
- Added
- Removed
-
trunk/MESOSCALE/LMD_MM_MARS/SRC/PYTHON/examples/scripts/find_devils.py
r310 r349 27 27 28 28 ### LOAD NETCDF DATA 29 filename = "psfc.nc"29 #filename = "/home/aymeric/Big_Data/psfc.nc" 30 30 nc = Dataset(filename) 31 31 psfc = nc.variables["PSFC"] … … 36 36 allsizesx = [] 37 37 allsizesy = [] 38 depression = [] 38 39 stride = 1 #5 39 40 for i in range(0,shape[0],stride): … … 52 53 fac = 3.5 53 54 #fac = 2.5 55 fac = 3. 54 56 lim = ave - fac*std 55 57 where = np.where(psfc2d < lim) 56 58 ############### END CRITERION 59 60 depression = np.append(depression,np.ravel(psfc2d[where])-ave) 57 61 58 62 lab = np.zeros(np.array(psfc2d).shape) ## points to be treated by the minimum_position routine … … 115 119 allsizesy.sort() 116 120 117 return allsizesx, allsizesy 121 return allsizesx, allsizesy, depression 118 122 119 123 ######################################################################### … … 125 129 import matplotlib.mlab as mlab 126 130 import mymath as mym 131 import myplot as myp 132 133 import plfit 134 import plplot 135 import randht 136 import plpva 127 137 128 138 save = True 129 139 save = False 140 pression = False 141 pression = True 130 142 131 143 if save: 132 allsizesx, allsizesy = getsize("psfc.nc")144 allsizesx, allsizesy, depression = getsize("/home/aymeric/Big_Data/psfc.nc") 133 145 ### sauvegarde texte pour inspection 134 146 mym.writeascii(allsizesx,'allsizex.txt') 135 147 mym.writeascii(allsizesy,'allsizey.txt') 148 mym.writeascii(depression,'alldepression.txt') 136 149 ### sauvegarde binaire pour utilisation python 137 150 myfile = open('allsizex.bin', 'wb') … … 141 154 pickle.dump(allsizesy, myfile) 142 155 myfile.close() 156 myfile = open('alldepression.bin', 'wb') 157 pickle.dump(depression, myfile) 158 myfile.close() 143 159 144 160 ### load files … … 147 163 myfile = open('allsizey.bin', 'r') 148 164 allsizesy = pickle.load(myfile) 149 150 ### append sizes 151 plothist = np.append(allsizesx,allsizesy) 165 myfile = open('alldepression.bin', 'r') 166 depression = pickle.load(myfile) 167 depression = np.array(abs(depression))#*1000. 168 169 ### sizes 170 #plothist = np.append(allsizesx,allsizesy) 152 171 plothist = allsizesx 153 #plothist = allsizesy 172 if pression: plothist = depression 154 173 plothist.sort() 155 156 ### make bins 174 print 'mean ', np.mean(plothist,dtype=np.float64) 175 print 'std ', np.std(plothist,dtype=np.float64) 176 print 'max ', np.max(plothist) 177 print 'min ', np.min(plothist) 178 print 'len ', len(plothist) 179 180 181 ### MAKE BINS 157 182 nbins = 100 158 183 zebins = [2.0] … … 165 190 zebins = [2./np.sqrt(2.)] ## ne pas tomber sur une dizaine ronde 166 191 nbins = 200 167 zebins = [0.2/np.sqrt(2.)] ## ne pas tomber sur une dizaine ronde 192 193 if pression: zebins = [0.3] 168 194 169 195 for i in range(0,nbins): zebins.append(zebins[i]*np.sqrt(2)) 170 196 zebins = np.array(zebins) 171 ### select reasonable bins for DD 172 zebins = zebins [ zebins > 10. ] 173 zebins = zebins [ zebins < 1000. ] 174 #print 'bins ',zebins 197 #### select reasonable bins for DD 198 if not pression: 199 zebins = zebins [ zebins > 15. ] 200 zebins = zebins [ zebins < 1000. ] 201 else: 202 zebins = zebins [ zebins < 10. ] 175 203 print 'corrected bins ',zebins 176 print 'max value ',mym.max(plothist),mym.max(allsizesx),mym.max(allsizesy)177 178 #plothist = [20.,30.,40.,50.,70.,100.,130.,190.,260.,370.,520.] ## pour calibrer179 204 180 205 #### HISTOGRAM 206 plt.figure(1) 181 207 plt.hist( plothist,\ 182 208 log=True,\ 183 209 bins=zebins,\ 184 210 # cumulative=-1,\ 211 normed=True,\ 185 212 ) 186 213 plt.xscale('log') 187 plt.show() 188 214 if pression: plt.xlabel('Pressure (Pa)') 215 else: plt.xlabel('Diameter (m)') 216 plt.ylabel('Population (normalized)') 217 if pression: prefix="p" 218 else: prefix="" 219 myp.makeplotres(prefix+"histogram",res=200,disp=False) 220 plt.close(1) 221 222 ### COMPARED HISTOGRAMS 223 ### --- FIT WITH POWER LAW 224 if pression: [alpha, xmin, L] = plfit.plfit(plothist,'xmin',0.3) 225 else: [alpha, xmin, L] = plfit.plfit(plothist,'limit',20.) 226 print alpha,xmin 227 228 #a = plpva.plpva(plothist,0.75,'xmin',0.75) 229 #print a 230 231 #### DEUXIEME ROUTINE 232 ####IL FAUT UTILISER LE DISCRET POUR LA TAILLE !!! 233 #if pression: myplfit = plfit.plfit(plothist,verbose=True,xmin=0.75) 234 #else: myplfit = plfit.plfit(plothist,verbose=True,xmin=20.) 235 #myplfit.plotppf() 236 #plt.show() 237 #exit() 238 239 240 #plt.figure(1) 241 #h = plplot.plplot(plothist,xmin,alpha) 242 #myp.makeplotres(prefix+"fit",res=200,disp=False) 243 plt.figure(2) 244 ### --- POWER LAW (factor does not really matter) 245 power = (xmin/2.2)*np.array(randht.randht(10000,'powerlaw',alpha)) 246 #power = (xmin/2.2)*np.array(randht.randht(10000,'cutoff',alpha,10.)) ##marche pas si trop grand 247 print 'mean ', np.mean(power,dtype=np.float64) 248 ### --- EXPONENTIAL LAW 249 expo = randht.randht(10000,'exponential',1./(np.mean(power,dtype=np.float64)*1.00)) 250 print 'mean ', np.mean(expo,dtype=np.float64) 251 ### --- PLOT 252 plt.hist( [plothist,power,expo],\ 253 label=['LES vortices','Power law '+'{:.1f}'.format(alpha),'Exponential law'],\ 254 log=True,\ 255 bins=zebins,\ 256 # cumulative=-1,\ 257 normed=True,\ 258 ) 259 plt.legend() 260 plt.xscale('log') 261 if pression: plt.xlabel('Pressure (Pa)') 262 else: plt.xlabel('Diameter (m)') 263 plt.ylabel('Population (normalized)') 264 myp.makeplotres(prefix+"comparison",res=200,disp=False) 265 plt.close(2) 266 267 ######################## 268 ######################## 269 zebins = [30.,42.,60.,84.,120.,170.,240.,340.] 270 plothist = [] 271 plothist = np.append(plothist,30 *np.ones(306)) 272 plothist = np.append(plothist,42 *np.ones(58) ) 273 plothist = np.append(plothist,60 *np.ones(66) ) 274 plothist = np.append(plothist,84 *np.ones(41) ) 275 plothist = np.append(plothist,120*np.ones(19) ) 276 plothist = np.append(plothist,170*np.ones(9) ) 277 plothist = np.append(plothist,240*np.ones(2) ) 278 plothist = np.append(plothist,340*np.ones(1) ) 279 280 #zebins = [50.,71.,100.,141.,200.,282.,400.] 281 #plothist = [] 282 #plothist = np.append(plothist,50. *np.ones(36)) 283 #plothist = np.append(plothist,71. *np.ones(18) ) 284 #plothist = np.append(plothist,100. *np.ones(12) ) 285 #plothist = np.append(plothist,141. *np.ones(6) ) 286 #plothist = np.append(plothist,200.*np.ones(4) ) 287 #plothist = np.append(plothist,282.*np.ones(1) ) 288 #plothist = np.append(plothist,400.*np.ones(2) ) 289 290 plt.figure(3) 291 [alpha, xmin, L] = plfit.plfit(plothist,'xmin',30)#50.) 292 print alpha,xmin 293 #a = plpva.plpva(plothist,30,'xmin',30) 294 h = plplot.plplot(plothist,xmin,alpha) 295 plt.loglog(h[0], h[1], 'k--',linewidth=2) 296 plt.hist( plothist,\ 297 log=True,\ 298 bins=zebins,\ 299 # cumulative=-1,\ 300 normed=True,\ 301 ) 302 plt.xscale('log') 303 plt.xlabel('Pressure (micro Pa)') 304 plt.ylabel('Population (normalized)') 305 myp.makeplotres("data",res=200,disp=False) 306 307 #plt.figure(4) 308 #[alpha, xmin, L] = plfit.plfit(plothist,'xmin',50.) #,'xmin',30.) 309 #print alpha,xmin 310 #h = plplot.plplot(plothist,xmin,alpha) 311 #myp.makeplotres("datafit",res=200,disp=False) -
trunk/MESOSCALE/LMD_MM_MARS/SRC/PYTHON/mymath.py
r345 r349 1 1 def min (field,axis=None): 2 2 import numpy as np 3 return np.array(field).min(axis=axis) 3 if field is None: return None 4 else: return np.array(field).min(axis=axis) 4 5 5 6 def max (field,axis=None): … … 10 11 def mean (field,axis=None): 11 12 import numpy as np 12 return np.array(field).mean(axis=axis) 13 if field is None: return None 14 else: return np.array(field).mean(axis=axis) 13 15 14 16 def deg (): -
trunk/MESOSCALE/LMD_MM_MARS/SRC/PYTHON/myplot.py
r345 r349 5 5 exit() 6 6 return 7 8 ## Author: AS 9 def adjust_length (tab, zelen): 10 from numpy import ones 11 if tab is None: 12 outtab = ones(zelen) * -999999 13 else: 14 if zelen != len(tab): 15 print "not enough or too much values... setting same values all variables" 16 outtab = ones(zelen) * tab[0] 17 else: 18 outtab = tab 19 return outtab 7 20 8 21 ## Author: AS … … 48 61 ### it would be actually better to name d4 d3 d2 d1 as t z y x 49 62 import numpy as np 50 from mymath import max 63 from mymath import max,mean 51 64 dimension = np.array(input).ndim 52 65 shape = np.array(input).shape 66 #print 'd1,d2,d3,d4: ',d1,d2,d3,d4 53 67 print 'dim,shape: ',dimension,shape 54 68 output = input … … 71 85 elif max(d1) >= shape[2]: error = True 72 86 elif d4 is not None and d2 is not None and d1 is not None: output = input[d4,d2,d1] 73 elif d4 is not None and d2 is not None: output =np.mean(input[d4,:,:],axis=0); output=np.mean(output[d2,:],axis=0)74 elif d4 is not None and d1 is not None: output =np.mean(input[d4,:,:],0); output=np.mean(output[:,d1],1)75 elif d2 is not None and d1 is not None: output =np.mean(input[:,d2,:],axis=1); output=np.mean(output[:,d1],axis=1)76 elif d1 is not None: output = np.mean(input[:,:,d1],axis=2)77 elif d2 is not None: output = np.mean(input[:,d2,:],axis=1)78 elif d4 is not None: output = np.mean(input[d4,:,:],axis=0)87 elif d4 is not None and d2 is not None: output = mean(input[d4,:,:],axis=0); output=mean(output[d2,:],axis=0) 88 elif d4 is not None and d1 is not None: output = mean(input[d4,:,:],axis=0); output=mean(output[:,d1],axis=1) 89 elif d2 is not None and d1 is not None: output = mean(input[:,d2,:],axis=1); output=mean(output[:,d1],axis=1) 90 elif d1 is not None: output = mean(input[:,:,d1],axis=2) 91 elif d2 is not None: output = mean(input[:,d2,:],axis=1) 92 elif d4 is not None: output = mean(input[d4,:,:],axis=0) 79 93 elif dimension == 4: 80 94 if max(d4) >= shape[0]: error = True … … 87 101 elif d4 is not None and d2 is not None and d1 is not None: output = input[d4,:,d2,d1] 88 102 elif d3 is not None and d2 is not None and d1 is not None: output = input[:,d3,d2,d1] 89 elif d4 is not None and d3 is not None: output = np.mean(input[d4,:,:,:],0); output = np.mean(output[d3,:,:],0)90 elif d4 is not None and d2 is not None: output = np.mean(input[d4,:,:,:],0); output = np.mean(output[:,d2,:],1)91 elif d4 is not None and d1 is not None: output = np.mean(input[d4,:,:,:],0); output = np.mean(output[:,:,d1],2)92 elif d3 is not None and d2 is not None: output = np.mean(input[:,d3,:,:],1); output = np.mean(output[:,d2,:],1)93 elif d3 is not None and d1 is not None: output = np.mean(input[:,d3,:,:],1); output = np.mean(output[:,:,d1],0)94 elif d2 is not None and d1 is not None: output = np.mean(input[:,:,d2,:],2); output = np.mean(output[:,:,d1],2)103 elif d4 is not None and d3 is not None: output = mean(input[d4,:,:,:],axis=0); output = mean(output[d3,:,:],axis=0) 104 elif d4 is not None and d2 is not None: output = mean(input[d4,:,:,:],axis=0); output = mean(output[:,d2,:],axis=1) 105 elif d4 is not None and d1 is not None: output = mean(input[d4,:,:,:],axis=0); output = mean(output[:,:,d1],axis=2) 106 elif d3 is not None and d2 is not None: output = mean(input[:,d3,:,:],axis=1); output = mean(output[:,d2,:],axis=1) 107 elif d3 is not None and d1 is not None: output = mean(input[:,d3,:,:],axis=1); output = mean(output[:,:,d1],axis=0) 108 elif d2 is not None and d1 is not None: output = mean(input[:,:,d2,:],axis=2); output = mean(output[:,:,d1],axis=2) 95 109 elif d1 is not None: output = input[:,:,:,d1] 96 110 elif d2 is not None: output = input[:,:,d2,:] … … 759 773 # output : all indexes to be taken into account for reducing field 760 774 import numpy as np 775 if ( np.array(axis).ndim == 2): 776 axis = axis[:,0] 761 777 if saxis is None: 762 778 zeindex = None … … 820 836 #print "define_axis", x, y 821 837 return what_I_plot,x,y 838 839 # Author: TN + AS 840 def determineplot(slon, slat, svert, stime): 841 nlon = 1 # number of longitudinal slices -- 1 is None 842 nlat = 1 843 nvert = 1 844 ntime = 1 845 nslices = 1 846 if slon is not None: 847 nslices = nslices*len(slon) 848 nlon = len(slon) 849 if slat is not None: 850 nslices = nslices*len(slat) 851 nlat = len(slat) 852 if svert is not None: 853 nslices = nslices*len(svert) 854 nvert = len(svert) 855 if stime is not None: 856 nslices = nslices*len(stime) 857 ntime = len(stime) 858 #else: 859 # nslices = 2 860 861 mapmode = 0 862 if slon is None and slat is None: 863 mapmode = 1 # in this case we plot a map, with the given projection 864 #elif proj is not None: 865 # print "WARNING: you specified a", proj,\ 866 # "projection but asked for slices", slon,"in longitude and",slat,"in latitude" 867 print "mapmode: ", mapmode 868 869 return nlon, nlat, nvert, ntime, mapmode, nslices -
trunk/MESOSCALE/LMD_MM_MARS/SRC/PYTHON/planetoplot.py
r345 r349 1 #!/usr/bin/env python 2 3 ### A. Spiga -- LMD -- 30/06/2011 to 10/07/2011 4 ### T.Navarro -- LMD -- 10/2011 5 ### Thanks to A. Colaitis for the parser trick 6 7 8 #################################### 9 #################################### 10 ### The main program to plot vectors 1 ####################### 2 ##### PLANETOPLOT ##### 3 ####################### 4 5 ### A. Spiga -- LMD -- 06~09/2011 -- General building and mapping capabilities 6 ### T. Navarro -- LMD -- 10~11/2011 -- Improved use for GCM and added sections + 1Dplot capabilities 7 11 8 def planetoplot (namefiles,\ 12 9 vertmode,\ … … 49 46 fmtvar,definecolorvec,defcolorb,getprefix,putpoints,calculate_bounds,errormess,definesubplot,\ 50 47 zoomset,getcoorddef,getwinddef,whatkindfile,reducefield,bounds,getstralt,getfield,smooth,nolow,\ 51 getname,localtime,polarinterv,getsindex,define_axis 48 getname,localtime,polarinterv,getsindex,define_axis,determineplot 52 49 from mymath import deg,max,min,mean 53 50 from matplotlib.pyplot import contour,contourf, subplot, figure, rcParams, savefig, colorbar, pcolor, show, plot, clabel … … 56 53 from numpy.core.defchararray import find 57 54 58 #whichmode = "" 59 nlon = 1 # number of longitudinal slices -- 1 is None 60 nlat = 1 61 nvert = 1 62 ntime = 1 63 nslices = 1 64 if slon is not None: 65 nslices = nslices*len(slon) 66 nlon = len(slon) 67 if slat is not None: 68 nslices = nslices*len(slat) 69 nlat = len(slat) 70 if svert is not None: 71 nslices = nslices*len(svert) 72 nvert = len(svert) 73 if stime is not None: 74 nslices = nslices*len(stime) 75 ntime = len(stime) 76 #else: 77 # nslices = 2 78 numplot = len(namefiles)*nslices 55 ################################ 56 ### Which plot needs to be done? 57 nlon, nlat, nvert, ntime, mapmode, nslices = determineplot(slon, slat, svert, stime) 58 if mapmode == 0: winds=False 59 if not isinstance(namefiles, np.ndarray): namefiles = [namefiles] 60 zelen = len(namefiles) 61 numplot = zelen*nslices 62 print "len(namefiles), nslices, numplot: ", zelen, nslices, numplot 63 all_var = [[]]*zelen 64 all_var2 = [[]]*zelen 65 all_title = [[]]*zelen 79 66 80 mapmode = 081 if slon is None and slat is None:82 mapmode = 1 # in this case we plot a map, with the given projection83 elif proj is not None:84 print "WARNING: you specified a", proj,\85 "projection but asked for slices", slon,"in longitude and",slat,"in latitude"86 print "mapmode", mapmode87 88 89 all_var = [[]]*len(namefiles)90 all_var2 = [[]]*len(namefiles)91 all_title = [[]]*len(namefiles)92 93 print "len(namefiles), nslices", len(namefiles), nslices94 print "numplot", numplot95 96 67 ######################### 97 68 ### Loop over the files initially separated by comas to be plotted on the same figure … … 106 77 ################################## 107 78 ### Initial checks and definitions 108 typefile = whatkindfile(nc) ## TYPEFILE 79 ### ... TYPEFILE 80 typefile = whatkindfile(nc) 109 81 if firstfile: 110 82 typefile0 = typefile 111 83 elif typefile != typefile0: 112 errormess("Not the same files !", [typefile0, typefile]) 113 if var not in nc.variables: var = False ## VAR 114 if winds: ## WINDS 84 errormess("Not the same kind of files !", [typefile0, typefile]) 85 ### ... VAR 86 if var not in nc.variables: var = False 87 ### ... WINDS 88 if winds: 115 89 [uchar,vchar,metwind] = getwinddef(nc) 116 90 if uchar == 'not found': winds = False 117 91 if not var and not winds: errormess("please set at least winds or var",printvar=nc.variables) 118 [lon2d,lat2d] = getcoorddef(nc) ## COORDINATES, could be moved below 119 if proj == None: proj = getproj(nc) ## PROJECTION 120 121 lat = nc.variables["latitude"][:] 122 lon = nc.variables["longitude"][:] 123 time = nc.variables["Time"][:] 124 vert = nc.variables["altitude"][:] 125 if firstfile: 126 lat0 = lat 127 elif len(lat0) != len(lat): 128 errormess("Not the same latitude lengths !", [len(lat0), len(lat)]) 129 elif sum((lat == lat0) == False) != 0: 130 errormess("Not the same latitudes !", [lat,lat0]) 131 # Faire d'autre checks sur les compatibilites entre fichiers!! 92 ### ... COORDINATES, could be moved below 93 [lon2d,lat2d] = getcoorddef(nc) 94 ### ... PROJECTION 95 if proj == None: proj = getproj(nc) 96 97 ########################################################## 98 if typefile == "gcm": 99 lat = nc.variables["latitude"][:] 100 lon = nc.variables["longitude"][:] 101 time = nc.variables["Time"][:] 102 vert = nc.variables["altitude"][:] 103 #if firstfile: 104 # lat0 = lat 105 #elif len(lat0) != len(lat): 106 # errormess("Not the same latitude lengths !", [len(lat0), len(lat)]) 107 #elif sum((lat == lat0) == False) != 0: 108 # errormess("Not the same latitudes !", [lat,lat0]) 109 ## Faire d'autre checks sur les compatibilites entre fichiers!! 110 ########################################################## 132 111 133 112 if firstfile: … … 143 122 ### Name for title and graphics save file 144 123 basename = getname(var=var,winds=winds,anomaly=anomaly) 145 basename = basename + getstralt(nc, nvert) ## can be moved elsewhere for a more generic routine124 basename = basename + getstralt(nc,vertmode) ## can be moved elsewhere for a more generic routine 146 125 147 print "var", var 148 print "var2", var2 149 #print all_var 150 #print nc 126 print "var, var2: ", var, var2 151 127 if var: all_var[k] = getfield(nc,var) 152 128 if var2: all_var2[k] = getfield(nc,var2) … … 173 149 elif numplot <= 0: itstep = 1 174 150 175 ### Map projection176 if mapmode == 1:177 m = define_proj(proj,wlon,wlat,back=back)178 x, y = m(lon2d, lat2d)179 180 151 #for nplot in range(numplot): 181 152 while error is False: … … 201 172 else: 202 173 found_lct = True 203 204 205 ## get all indexes to be taken into account for this subplot and then reduce field 206 ## We plot 1) all lon slices 2) all lat slices 3) all vert slices 4) all time slices and then go to the next slice 207 #print "(nplot-1)%nlon", (nplot-1)%nlon 208 indexlon = getsindex(slon,(nplot-1)%nlon,lon) 209 #print "indexlon", indexlon 210 indexlat = getsindex(slat,((nplot-1)//nlon)%nlat,lat) 211 indexvert = getsindex(svert,((nplot-1)//(nlon*nlat))%nvert,vert) 212 indextime = getsindex(stime,((nplot-1)//(nlon*nlat*nvert))%ntime,time) 213 index_f = ((nplot-1)//(nlon*nlat*nvert*ntime))%len(namefiles) 214 #print "index lon,lat,vert,time", max(indexlon), max(indexlat), max(indexvert), max(indextime) 174 175 ### Map projection 176 if mapmode == 1: 177 m = define_proj(proj,wlon,wlat,back=back) 178 x, y = m(lon2d, lat2d) 179 180 #################################################################### 181 if typefile in ['mesoapi','meso']: 182 indexlon = None 183 indexlat = None 184 indexvert = vertmode 185 indextime = itime 186 nlon = 1 187 nlat = 1 188 nvert = 1 189 ntime = 1 190 index_f = ((nplot-1)//(nlon*nlat*nvert*ntime))%len(namefiles) 191 print "index lon,lat,vert,time", max(indexlon), max(indexlat), max(indexvert), max(indextime) 192 elif typefile in ['gcm']: 193 ## get all indexes to be taken into account for this subplot and then reduce field 194 ## We plot 1) all lon slices 2) all lat slices 3) all vert slices 4) all time slices and then go to the next slice 195 #print "(nplot-1)%nlon", (nplot-1)%nlon 196 indexlon = getsindex(slon,(nplot-1)%nlon,lon) 197 print "indexlon", indexlon 198 indexlat = getsindex(slat,((nplot-1)//nlon)%nlat,lat) 199 indexvert = getsindex(svert,((nplot-1)//(nlon*nlat))%nvert,vert) 200 indextime = getsindex(stime,((nplot-1)//(nlon*nlat*nvert))%ntime,time) 201 index_f = ((nplot-1)//(nlon*nlat*nvert*ntime))%len(namefiles) 202 #print "index lon,lat,vert,time", max(indexlon), max(indexlat), max(indexvert), max(indextime) 203 #################################################################### 215 204 216 205 #### Contour plot 217 206 if var2: 218 207 what_I_plot, error = reducefield(all_var2[index_f], d4=indextime, d1=indexlon, d2=indexlat , d3=indexvert ) 219 what_I_plot = what_I_plot*mult208 #what_I_plot = what_I_plot*mult 220 209 if not error: 221 if typefile in ['mesoapi','meso']: what_I_plot = dumpbdy(what_I_ contour,6)210 if typefile in ['mesoapi','meso']: what_I_plot = dumpbdy(what_I_plot,6) 222 211 zevmin, zevmax = calculate_bounds(what_I_plot) 223 zelevels = np.linspace(zevmin,zevmax,num=ndiv) 212 zelevels = np.linspace(zevmin,zevmax,num=ndiv+1) #20) 213 if var2 == 'HGT': zelevels = np.arange(-10000.,30000.,2000.) 224 214 if mapmode == 0: 225 215 x, y = define_axis(lon,lat,vert,time,indexlon,indexlat,indexvert,\ … … 227 217 ### If we plot a 2-D field 228 218 if len(what_I_plot.shape) is 2: 229 cs = contour(x,y,what_I_plot, zelevels, colors='k', linewidths = 1 ) # colors='w' )# , alpha=0.5)230 clabel(cs,fmt = '%1.2e')219 cs = contour(x,y,what_I_plot, zelevels, colors='k', linewidths = 1 ) #0.33 colors='w' )# , alpha=0.5) 220 if typefile in ['gcm']: clabel(cs,fmt = '%1.2e') 231 221 ### If we plot a 1-D field 232 222 elif len(what_I_plot.shape) is 1: … … 256 246 if len(what_I_plot.shape) is 2: 257 247 if mapmode == 0: 258 what_I_plot, x, y = define_axis(lon,lat,vert,time,indexlon,indexlat,indexvert,\248 what_I_plot, x, y = define_axis(lon,lat,vert,time,indexlon,indexlat,indexvert,\ 259 249 indextime,what_I_plot, len(all_var[index_f].shape),vertmode) 260 250 if not tile: … … 263 253 print "what_I_plot.shape", what_I_plot.shape 264 254 print "x.shape, y.shape", x.shape, y.shape 265 zelevels = np.linspace(zevmin,zevmax,num=ndiv )255 zelevels = np.linspace(zevmin,zevmax,num=ndiv+1) 266 256 #contourf(what_I_plot, zelevels, cmap = palette ) 267 257 contourf(x,y,what_I_plot, zelevels, cmap = palette ) … … 274 264 #colorbar() 275 265 colorbar(fraction=0.05,pad=0.03,format=fmtvar(fvar.upper()),\ 276 ticks=np.linspace(zevmin,zevmax,min([ndiv ,20])),\266 ticks=np.linspace(zevmin,zevmax,min([ndiv+1,20])),\ 277 267 extend='neither',spacing='proportional') 278 268 # both min max neither … … 295 285 else: 296 286 errormess("There is an error in reducing field !") 297 287 288 ### Vector plot --- a adapter 289 if winds: 290 vecx, error = reducefield( getfield(nc,uchar), d4=indextime, d3=indexvert ) 291 vecy, error = reducefield( getfield(nc,vchar), d4=indextime, d3=indexvert ) 292 #what_I_plot, error = reducefield(all_var[index_f], d4=indextime, d1=indexlon, d2=indexlat , d3=indexvert ) 293 if not error: 294 if typefile in ['mesoapi','meso']: 295 [vecx,vecy] = [dumpbdy(vecx,6,stag=uchar), dumpbdy(vecy,6,stag=vchar)] 296 key = True 297 elif typefile in ['gcm']: 298 key = False 299 if metwind: [vecx,vecy] = m.rotate_vector(vecx, vecy, lon2d, lat2d) 300 if var == False: colorvec = definecolorvec(back) 301 else: colorvec = definecolorvec(colorb) 302 vectorfield(vecx, vecy,\ 303 x, y, stride=stride, csmooth=2,\ 304 #scale=15., factor=300., color=colorvec, key=key) 305 scale=20., factor=250., color=colorvec, key=key) 306 #200. ## or csmooth=stride 298 307 299 308 ### Next subplot 300 plottitle = basename+' '+namefiles[index_f]301 309 if typefile in ['mesoapi','meso']: 310 plottitle = basename 302 311 if addchar: plottitle = plottitle + addchar + "_LT"+str(ltst) 303 312 else: plottitle = plottitle + "_LT"+str(ltst) 313 else: 314 plottitle = basename+' '+namefiles[index_f] 304 315 if mult != 1: plottitle = str(mult) + "*" + plottitle 305 316 if zetitle != "fill": plottitle = zetitle … … 314 325 ptitle( plottitle ) 315 326 itime += itstep 316 if nplot == numplot:327 if nplot >= numplot: 317 328 error = True 318 329 nplot += 1 … … 356 367 ### Now the end 357 368 return zeplot 358 359 ##############################360 ### A specific stuff for below361 def adjust_length (tab, zelen):362 from numpy import ones363 if tab is None:364 outtab = ones(zelen) * -999999365 else:366 if zelen != len(tab):367 print "not enough or too much values... setting same values all variables"368 outtab = ones(zelen) * tab[0]369 else:370 outtab = tab371 return outtab372 373 ###########################################################################################374 ###########################################################################################375 ### What is below relate to running the file as a command line executable (very convenient)376 if __name__ == "__main__":377 import sys378 from optparse import OptionParser ### to be replaced by argparse379 from api_wrapper import api_onelevel380 from netCDF4 import Dataset381 from myplot import getlschar, separatenames, readslices382 from os import system383 import numpy as np384 385 #############################386 ### Get options and variables387 parser = OptionParser()388 parser.add_option('-f', '--file', action='append',dest='namefile', type="string", default=None, help='[NEEDED] name of WRF file (append). Plot files separated by comas in the same figure')389 parser.add_option('-l', '--level', action='store',dest='nvert', type="float", default=0, help='level (def=0)(-i 2: p,mbar)(-i 3,4: z,km)')390 parser.add_option('-p', '--proj', action='store',dest='proj', type="string", default=None, help='projection')391 parser.add_option('-b', '--back', action='store',dest='back', type="string", default=None, help='background image (def: None)')392 parser.add_option('-t', '--target', action='store',dest='target', type="string", default=None, help='destination folder')393 parser.add_option('-s', '--stride', action='store',dest='stride', type="int", default=3, help='stride vectors (def=3)')394 parser.add_option('-v', '--var', action='append',dest='var', type="string", default=None, help='variable color-shaded (append)')395 parser.add_option('-n', '--num', action='store',dest='numplot', type="int", default=2, help='plot number (def=2)(<0: plot LT -*numplot*)')396 parser.add_option('-i', '--interp', action='store',dest='interp', type="int", default=None, help='interpolation (2: p, 3: z-amr, 4:z-als)')397 parser.add_option('-c', '--color', action='store',dest='colorb', type="string", default="def", help='change colormap (nobar: no colorbar)')398 parser.add_option('-x', '--no-vect',action='store_false',dest='winds', default=True, help='no wind vectors')399 parser.add_option('-m', '--min', action='append',dest='vmin', type="float", default=None, help='bounding minimum value (append)')400 parser.add_option('-M', '--max', action='append',dest='vmax', type="float", default=None, help='bounding maximum value (append)')401 parser.add_option('-T', '--tiled', action='store_true',dest='tile', default=False, help='draw a tiled plot (no blank zone)')402 parser.add_option('-z', '--zoom', action='store',dest='zoom', type="float", default=None, help='zoom factor in %')403 parser.add_option('-N', '--no-api', action='store_true',dest='nocall', default=False, help='do not recreate api file')404 parser.add_option('-d', '--display',action='store_false',dest='display', default=True, help='do not pop up created images')405 parser.add_option('-e', '--itstep', action='store',dest='itstep', type="int", default=None, help='stride time (def=4)')406 parser.add_option('-H', '--hole', action='store_true',dest='hole', default=False, help='holes above max and below min')407 parser.add_option('-S', '--save', action='store',dest='save', type="string", default="gui", help='save mode (png,eps,svg,pdf or gui)(def=gui)')408 parser.add_option('-a', '--anomaly',action='store_true',dest='anomaly', default=False, help='compute and plot relative anomaly in %')409 parser.add_option('-w', '--with', action='store',dest='var2', type="string", default=None, help='variable contoured')410 parser.add_option('--div', action='store',dest='ndiv', type="int", default=10, help='number of divisions in colorbar (def: 10)')411 parser.add_option('-F', '--first', action='store',dest='first', type="int", default=1, help='first subscript to plot (def: 1)')412 parser.add_option('--mult', action='store',dest='mult', type="float", default=1., help='a multiplicative factor to plotted field')413 parser.add_option('--title', action='store',dest='zetitle', type="string", default="fill",help='customize the whole title')414 #parser.add_option('-V', action='store', dest='comb', type="float", default=None, help='a defined combination of variables')415 416 ############# T.N. changes417 #parser.add_option('-o','--operation',action='store',dest='operation',type="string", default=None ,help='matrix of operations between files (for now see code, sorry)')418 parser.add_option('--lat', action='append',dest='slat',type="string", default=None, help='slices along latitude. One value, or two values separated by comas for averaging')419 parser.add_option('--lon', action='append',dest='slon', type="string", default=None, help='slices along longitude. One value, or two values separated by comas for averaging')420 parser.add_option('--vert', action='append',dest='svert',type="string", default=None, help='slices along vertical axis. One value, or two values separated by comas for averaging') # quelles coordonnees ?421 parser.add_option('--time', action='append',dest='stime',type="string", default=None, help='slices along time. One value, or two values separated by comas for averaging') # quelles coordonnees ?422 423 (opt,args) = parser.parse_args()424 if opt.namefile is None:425 print "I want to eat one file at least ! Use winds.py -f name_of_my_file. Or type winds.py -h"426 exit()427 if opt.var is None and opt.anomaly is True:428 print "Cannot ask to compute anomaly if no variable is set"429 exit()430 print "Options:", opt431 432 #listvar = ''433 #if opt.var is None:434 # zerange = [-999999]435 #else:436 # zelen = len(opt.var)437 # zerange = range(zelen)438 # #if zelen == 1: listvar = opt.var[0] + ','439 # #else :440 # for jjj in zerange: listvar += opt.var[jjj] + ','441 # listvar = listvar[0:len(listvar)-1]442 # vmintab = adjust_length (opt.vmin, zelen)443 # vmaxtab = adjust_length (opt.vmax, zelen)444 445 print "namefile, length", opt.namefile, len(opt.namefile)446 447 zeslat = readslices(opt.slat)448 zeslon = readslices(opt.slon)449 zesvert = readslices(opt.svert)450 zestime = readslices(opt.stime)451 print "slat,zeslat", opt.slat, zeslat452 print "slon,zeslon", opt.slon, zeslon453 print "svert,zesvert", opt.svert, zesvert454 print "stime,zestime", opt.stime, zestime455 456 457 for i in range(len(opt.namefile)):458 for j in range(len(opt.var)):459 460 zenamefiles = separatenames(opt.namefile[i])461 print "zenamefiles", zenamefiles462 463 if opt.vmin is not None : zevmin = opt.vmin[min(i,len(opt.vmin)-1)]464 else: zevmin = None465 if opt.vmax is not None : zevmax = opt.vmax[min(i,len(opt.vmax)-1)]466 else: zevmax = None467 print "vmin, zevmin", opt.vmin, zevmin468 print "vmax, zevmax", opt.vmax, zevmax469 470 zevar = separatenames(opt.var[j])471 zevar = zevar[0]472 print "var, zevar", opt.var, zevar473 474 #checkcoherence(len(zenamefiles),len(opt.slat),len(opt.slon),len(opt.stime))475 476 zefile = zenamefiles[0]477 478 zelevel = opt.nvert479 stralt = None480 [lschar,zehour,zehourin] = getlschar ( zefile ) ## getlschar from wrfout (or simply return "" if another file)481 #print "lschar ",lschar482 #print "zehour ",zehour483 #print "zehourin ",zehourin484 485 #####################################################486 ### Call Fortran routines for vertical interpolations487 if opt.interp is not None:488 if opt.nvert is 0 and opt.interp is 4: zelevel = 0.010489 ### winds or no winds490 if opt.winds : zefields = 'uvmet'491 else : zefields = ''492 ### var or no var493 #if opt.var is None : pass494 if zefields == '' : zefields = listvar495 else : zefields = zefields + "," + listvar496 if opt.var2 is not None : zefields = zefields + "," + opt.var2497 print zefields498 zefile = api_onelevel ( path_to_input = '', \499 input_name = zefile, \500 fields = zefields, \501 interp_method = opt.interp, \502 onelevel = zelevel, \503 nocall = opt.nocall )504 print zefile505 zelevel = 0 ## so that zelevel could play again the role of nvert506 507 508 #############509 ### Main call510 name = planetoplot (zenamefiles,int(zelevel),\511 proj=opt.proj,back=opt.back,target=opt.target,stride=opt.stride,var=zevar,\512 numplot=opt.numplot,colorb=opt.colorb,winds=opt.winds,\513 addchar=lschar,interv=[zehour,zehourin],vmin=zevmin,vmax=zevmax,\514 tile=opt.tile,zoom=opt.zoom,display=opt.display,\515 itstep=opt.itstep,hole=opt.hole,save=opt.save,\516 anomaly=opt.anomaly,var2=opt.var2,ndiv=opt.ndiv,first=opt.first,\517 mult=opt.mult,zetitle=opt.zetitle,\518 slon=zeslon,slat=zeslat,svert=zesvert,stime=zestime)519 print 'Done: '+name520 system("rm -f to_be_erased")521 522 #########################################################523 ### Generate a .sh file with the used command saved in it524 command = ""525 for arg in sys.argv: command = command + arg + ' '526 name = 'pycommand'527 f = open(name+'.sh', 'w')528 f.write(command)
Note: See TracChangeset
for help on using the changeset viewer.