Changeset 876 for trunk/UTIL/PYTHON/myplot.py
- Timestamp:
- Feb 11, 2013, 2:22:32 PM (12 years ago)
- File:
-
- 1 edited
Legend:
- Unmodified
- Added
- Removed
-
trunk/UTIL/PYTHON/myplot.py
r874 r876 1 2 import numpy as np 3 import netCDF4 4 1 5 ## Author: AS 2 6 def errormess(text,printvar=None): … … 8 12 ## Author: AS 9 13 def adjust_length (tab, zelen): 10 from numpy import ones11 14 if tab is None: 12 outtab = ones(zelen) * -99999915 outtab = np.ones(zelen) * -999999 13 16 else: 14 17 if zelen != len(tab): 15 18 print "not enough or too much values... setting same values all variables" 16 outtab = ones(zelen) * tab[0]19 outtab = np.ones(zelen) * tab[0] 17 20 else: 18 21 outtab = tab … … 31 34 ## Author: AS + AC 32 35 def localtime(time,lon,namefile): # lon is the mean longitude of the plot, not of the domain. central lon of domain is taken from cen_lon 33 import numpy as np34 from netCDF4 import Dataset35 36 ## THIS IS FOR MESOSCALE 36 nc = Dataset(namefile)37 nc = netCDF4.Dataset(namefile) 37 38 ## get start date and intervals 38 39 dt_hour=1. ; start=0. … … 93 94 94 95 ## Author: AS 96 def getfieldred (nc,var,indexlon,indexlat,indexvert,indextime): 97 dimension = len(nc.variables[var].dimensions) 98 ## this allows to get much faster and use much less memory esp. with large datasets 99 if dimension == 2: field = nc.variables[var][indextime,indexlon] 100 elif dimension == 3: field = nc.variables[var][indextime,indexlat,indexlon] 101 elif dimension == 4: field = nc.variables[var][indextime,indexvert,indexlat,indexlon] 102 elif dimension == 1: field = nc.variables[var][indextime] 103 return field 104 105 ## Author: AS 95 106 def getfield (nc,var): 107 dimension = len(nc.variables[var].dimensions) 96 108 ## this allows to get much faster (than simply referring to nc.variables[var]) 97 import numpy as np 98 dimension = len(nc.variables[var].dimensions) 99 #print " Opening variable with", dimension, "dimensions ..." 109 print " Opening variable",var," with", dimension, "dimensions ..." 100 110 if dimension == 2: field = nc.variables[var][:,:] 101 111 elif dimension == 3: field = nc.variables[var][:,:,:] … … 142 152 # The corresponding variable to call is UV or uvmet (to use api) 143 153 def windamplitude (nc,mode): 144 import numpy as np145 154 varinfile = nc.variables.keys() 146 155 if "U" in varinfile: zu=getfield(nc,'U') … … 177 186 # this only requires co2col so that you can concat.nc at low cost 178 187 def enrichment_factor(nc,lon,lat,time): 179 import numpy as np180 188 from myplot import reducefield 181 189 varinfile = nc.variables.keys() … … 213 221 # The corresponding variable to call is SLOPEXY 214 222 def slopeamplitude (nc): 215 import numpy as np216 223 varinfile = nc.variables.keys() 217 224 if "slopex" in varinfile: zu=getfield(nc,'slopex') … … 233 240 # The corresponding variable to call is DELTAT 234 241 def deltat0t1 (nc): 235 import numpy as np236 242 varinfile = nc.variables.keys() 237 243 if "tsurf" in varinfile: zu=getfield(nc,'tsurf') … … 251 257 ### it would be actually better to name d4 d3 d2 d1 as t z y x 252 258 ### ... note, anomaly is only computed over d1 and d2 for the moment 253 import numpy as np254 259 from mymath import max,mean,min,sum,getmask 255 260 csmooth = 12 ## a fair amount of grid points (too high results in high computation time) … … 444 449 from mymath import max,mean 445 450 from scipy import integrate 446 import numpy as np447 451 if yint and vert is not None and indice is not None: 448 452 if type(input).__name__=='MaskedArray': … … 483 487 rcParams['font.size'] = int( rcParams['font.size'] * 2. / 3. ) 484 488 elif numplot <= 6: 485 subv = 2 486 subh = 3 487 #fig.subplots_adjust(wspace = 0.4, hspace = 0.0) 488 fig.subplots_adjust(wspace = 0.5, hspace = 0.3) 489 subv = 3#2 490 subh = 2#3 491 ##fig.subplots_adjust(wspace = 0.4, hspace = 0.0) 492 #fig.subplots_adjust(wspace = 0.5, hspace = 0.3) 493 fig.subplots_adjust(wspace = 0.3, hspace = 0.5) 489 494 rcParams['font.size'] = int( rcParams['font.size'] * 1. / 2. ) 490 495 elif numplot <= 8: … … 531 536 ## Author: AS 532 537 def getlschar ( namefile, getaxis=False ): 533 from netCDF4 import Dataset534 538 from timestuff import sol2ls 535 from numpy import array536 539 from string import rstrip 537 540 import os as daos … … 542 545 namefile = namefiletest 543 546 #### we assume that wrfout is next to wrfout_z and wrfout_zabg 544 nc = Dataset(namefile)547 nc = netCDF4.Dataset(namefile) 545 548 zetime = None 546 549 days_in_month = [61, 66, 66, 65, 60, 54, 50, 46, 47, 47, 51, 56] … … 548 551 if 'Times' in nc.variables: 549 552 zetime = nc.variables['Times'][0] 550 shape = array(nc.variables['Times']).shape553 shape = np.array(nc.variables['Times']).shape 551 554 if shape[0] < 2: zetime = None 552 555 if zetime is not None \ … … 621 624 ## Author: AS 622 625 def polarinterv (lon2d,lat2d): 623 import numpy as np624 626 wlon = [np.min(lon2d),np.max(lon2d)] 625 627 ind = np.array(lat2d).shape[0] / 2 ## to get a good boundlat and to get the pole … … 629 631 ## Author: AS 630 632 def simplinterv (lon2d,lat2d): 631 import numpy as np632 633 return [[np.min(lon2d),np.max(lon2d)],[np.min(lat2d),np.max(lat2d)]] 633 634 … … 679 680 ## Author: AS + AC 680 681 def getcoorddef ( nc ): 681 import numpy as np682 682 ## getcoord2d for predefined types 683 683 typefile = whatkindfile(nc) … … 712 712 ## Author: AS 713 713 def getcoord2d (nc,nlat='XLAT',nlon='XLONG',is1d=False): 714 import numpy as np715 714 if nlon == "nothing" or nlat == "nothing": 716 715 print "NO LAT LON FIELDS. I AM TRYING MY BEST. I ASSUME GLOBAL FIELD." … … 740 739 ## FROM COOKBOOK http://www.scipy.org/Cookbook/SignalSmooth 741 740 def smooth1d(x,window_len=11,window='hanning'): 742 import numpy743 741 """smooth the data using a window with requested size. 744 742 This method is based on the convolution of a scaled window with the signal. … … 762 760 TODO: the window parameter could be the window itself if an array instead of a string 763 761 """ 764 x = n umpy.array(x)762 x = np.array(x) 765 763 if x.ndim != 1: 766 764 raise ValueError, "smooth only accepts 1 dimension arrays." … … 771 769 if not window in ['flat', 'hanning', 'hamming', 'bartlett', 'blackman']: 772 770 raise ValueError, "Window is on of 'flat', 'hanning', 'hamming', 'bartlett', 'blackman'" 773 s=n umpy.r_[x[window_len-1:0:-1],x,x[-1:-window_len:-1]]771 s=np.r_[x[window_len-1:0:-1],x,x[-1:-window_len:-1]] 774 772 #print(len(s)) 775 773 if window == 'flat': #moving average 776 w=n umpy.ones(window_len,'d')774 w=np.ones(window_len,'d') 777 775 else: 778 776 w=eval('numpy.'+window+'(window_len)') 779 y=n umpy.convolve(w/w.sum(),s,mode='valid')777 y=np.convolve(w/w.sum(),s,mode='valid') 780 778 return y 781 779 … … 789 787 ## FROM COOKBOOK http://www.scipy.org/Cookbook/SignalSmooth 790 788 def gauss_kern(size, sizey=None): 791 import numpy as np792 789 # Returns a normalized 2D gauss kernel array for convolutions 793 790 size = int(size) … … 832 829 ## factor regle toutes les longueurs (dont la reference). l'AUGMENTER pour raccourcir les vecteurs. 833 830 import matplotlib.pyplot as plt 834 import numpy as np835 831 #posx = np.min(x) - np.std(x) / 10. 836 832 #posy = np.min(y) - np.std(y) / 10. … … 874 870 def define_proj (char,wlon,wlat,back=None,blat=None,blon=None): 875 871 from mpl_toolkits.basemap import Basemap 876 import numpy as np877 872 import matplotlib as mpl 878 873 from mymath import max … … 978 973 ## Author: AS 979 974 def calculate_bounds(field,vmin=None,vmax=None): 980 import numpy as np981 975 from mymath import max,min,mean 982 976 ind = np.where(field < 9e+35) … … 1022 1016 ## Author : AC 1023 1017 def hole_bounds(what_I_plot,zevmin,zevmax): 1024 import numpy as np1025 1018 zi=0 1026 1019 for i in what_I_plot: … … 1264 1257 ## Author: TN 1265 1258 def separatenames (name): 1266 from numpy import concatenate1267 1259 # look for comas in the input name to separate different names (files, variables,etc ..) 1268 1260 if name is None: … … 1279 1271 else: 1280 1272 name1 = currentname[0:indexvir] 1281 names = concatenate((names,[name1]))1273 names = np.concatenate((names,[name1])) 1282 1274 currentname = currentname[indexvir+1:len(currentname)] 1283 1275 return names … … 1286 1278 ## Author: TN 1287 1279 def readslices(saxis): 1288 from numpy import empty1289 1280 if saxis == None: 1290 1281 zesaxis = None 1291 1282 else: 1292 zesaxis = empty((len(saxis),2))1283 zesaxis = np.empty((len(saxis),2)) 1293 1284 for i in range(len(saxis)): 1294 1285 a = separatenames(saxis[i]) … … 1304 1295 def readdata(data,datatype,coord1,coord2): 1305 1296 ## Read sparse data 1306 from numpy import empty1307 1297 if datatype == 'txt': 1308 1298 if len(data[coord1].shape) == 1: … … 1320 1310 ## Author: AS 1321 1311 def bidimfind(lon2d,lat2d,vlon,vlat,file=None): 1322 import numpy as np1323 1312 import matplotlib.pyplot as mpl 1324 1313 if vlat is None: array = (lon2d - vlon)**2 … … 1342 1331 # input : all the desired slices and the good index 1343 1332 # output : all indexes to be taken into account for reducing field 1344 import numpy as np1345 1333 if ( np.array(axis).ndim == 2): 1346 1334 axis = axis[:,0] … … 1364 1352 # x axis priority: 1/time 2/lon 3/lat 4/vertical 1365 1353 # To be improved !!!... 1366 from numpy import array,swapaxes1367 1354 x = None 1368 1355 y = None 1369 1356 count = 0 1370 what_I_plot = array(what_I_plot)1357 what_I_plot = np.array(what_I_plot) 1371 1358 shape = what_I_plot.shape 1372 1359 if indextime is None and len(time) > 1: … … 1394 1381 else: y = vert 1395 1382 count = count+1 1396 x = array(x)1397 y = array(y)1383 x = np.array(x) 1384 y = np.array(y) 1398 1385 print "CHECK SHAPE: what_I_plot, x, y", what_I_plot.shape, x.shape, y.shape 1399 1386 if len(shape) == 1: … … 1402 1389 elif len(shape) == 2: 1403 1390 if shape[1] == len(y) and shape[0] == len(x) and shape[0] != shape[1]: 1404 print "INFO: swapaxes: ",what_I_plot.shape,shape ; what_I_plot = swapaxes(what_I_plot,0,1)1391 print "INFO: swapaxes: ",what_I_plot.shape,shape ; what_I_plot = np.swapaxes(what_I_plot,0,1) 1405 1392 else: 1406 1393 if shape[0] != len(y): print "WARNING: shape[0] != len(y). Correcting." ; what_I_plot = what_I_plot[0:len(y),:] … … 1445 1432 vecx=None,vecy=None,stride=2 ): 1446 1433 ### an easy way to map a field over lat/lon grid 1447 import numpy as np1448 1434 import matplotlib.pyplot as mpl 1449 1435 from matplotlib.cm import get_cmap … … 1496 1482 specificname_gcm = ['enfact'] 1497 1483 1484 zncvar = znc.variables 1485 1498 1486 ## Check for variable in file: 1499 1487 if mode == 'check': 1500 1488 varname = zvarname 1501 varinfile=znc .variables.keys()1502 logical_novarname = zvarname not in znc .variables1489 varinfile=zncvar.keys() 1490 logical_novarname = zvarname not in zncvar 1503 1491 logical_nospecificname_meso = not ((ztypefile in ['meso']) and (zvarname in specificname_meso)) 1504 1492 logical_nospecificname_gcm = not ((ztypefile in ['gcm']) and (zvarname in specificname_gcm)) … … 1519 1507 all_var=get_tsat(yalt,tinput,zlon=ylon,zlat=ylat,zalt=yalt,ztime=ytime) 1520 1508 ### ----------- 2. wind amplitude 1521 elif ((zvarname in ['UV','uv','uvmet']) and (ztypefile in ['meso']) and (zvarname not in znc .variables)):1509 elif ((zvarname in ['UV','uv','uvmet']) and (ztypefile in ['meso']) and (zvarname not in zncvar)): 1522 1510 all_var=windamplitude(znc,'amplitude') 1523 elif ((zvarname in ['hodograph','hodograph_2']) and (ztypefile in ['meso']) and (zvarname not in znc .variables)):1511 elif ((zvarname in ['hodograph','hodograph_2']) and (ztypefile in ['meso']) and (zvarname not in zncvar)): 1524 1512 plot_x, plot_y = windamplitude(znc,zvarname) 1525 1513 if plot_x is not None: all_var=plot_x # dummy 1526 1514 else: all_var=plot_y ; plot_x = None ; plot_y = None # Hodograph type 2 is not 'xy' mode 1527 elif ((zvarname in ['slopexy','SLOPEXY']) and (ztypefile in ['meso']) and (zvarname not in znc .variables)):1515 elif ((zvarname in ['slopexy','SLOPEXY']) and (ztypefile in ['meso']) and (zvarname not in zncvar)): 1528 1516 all_var=slopeamplitude(znc) 1529 1517 ### ------------ 3. Near surface instability 1530 elif ((zvarname in ['DELTAT','deltat']) and (ztypefile in ['meso']) and (zvarname not in znc .variables)):1518 elif ((zvarname in ['DELTAT','deltat']) and (ztypefile in ['meso']) and (zvarname not in zncvar)): 1531 1519 all_var=deltat0t1(znc) 1532 1520 ### ------------ 4. Enrichment factor … … 1534 1522 all_var=enrichment_factor(znc,ylon,ylat,ytime) 1535 1523 ### ------------ 5. teta -> temp 1536 elif ((ztypefile in ['meso']) and (zvarname in ['tk']) and ('tk' not in znc .variables.keys())):1524 elif ((ztypefile in ['meso']) and (zvarname in ['tk']) and ('tk' not in zncvar.keys())): 1537 1525 all_var=teta_to_tk(znc) 1538 1526 else: … … 1549 1537 # (which is not efficient but it is still ok) and then, make the average (if the user wants to) 1550 1538 def spectrum(var,time,vert,lat,lon): 1551 import numpy as np1552 1539 fft=np.fft.fft(var,axis=1) 1553 1540 N=len(vert) … … 1565 1552 # Computes temperature from potential temperature for mesoscale files, without the need to use API, i.e. using natural vertical grid 1566 1553 def teta_to_tk(nc): 1567 import numpy as np1568 1554 varinfile = nc.variables.keys() 1569 1555 p0=610. … … 1588 1574 # 6/ in this slab, find the point at which the surface pressure is minimum 1589 1575 def find_devil(nc,indextime): 1590 import numpy as np1591 1576 from scipy import ndimage 1592 1577 from mymath import array2image,image2array
Note: See TracChangeset
for help on using the changeset viewer.