source: trunk/UTIL/PYTHON/examples/scripts/find_devils.py @ 781

Last change on this file since 781 was 349, checked in by aslmd, 13 years ago

PYTHON GRAPHICS: A REFERENCE VERSION FOR BOTH GCM AND MESOSCALE USE!

Merged recent changes by TN for better GCM handling + 1D/2D plots with AS mesoscale version [winds.py]

Now

  • there is a common function named planetoplot in planetoplot.py which supports both GCM and mesoscale plots

    this will be a common reference for future development

  • mesoscale users might want to use the script meso.py
  • GCM users might want to use the script gcm.py

Todo

  • a few capabilities that were in winds.py are broken in meso.py, this will be fixed soon. the 'old' reference script winds.py is still here anyway!
  • there is still a bug with 'ortho' projection with GCM fields. still searching...

Misc

  • A few modifications were done in myplot.py and mymath.py
  • Added a simple stupid little.py script illustrating very simple use of Python graphics
  • Added the script doing statistical analysis for dust devils
  • Property svn:executable set to *
File size: 10.2 KB
Line 
1#! /usr/bin/env python
2
3def detsize( xx, res=1, thres=3, loga=False ):
4    import numpy as np
5    import math
6    size = []
7    sizecalc = 1
8    diff = np.asarray( np.roll(xx,-1) - xx )
9    for i in diff:
10        if abs(i) > 1:
11            if sizecalc >= thres: 
12                if loga: addthis = math.log(sizecalc*res)
13                else:    addthis = sizecalc*res
14                size.append(addthis)
15            sizecalc = 1
16        else:
17            sizecalc += 1
18    return size
19
20def getsize(filename):
21
22    import numpy as np
23    from scipy.ndimage.measurements import minimum_position
24    from netCDF4 import Dataset
25    import matplotlib.pyplot as plt
26    import myplot as myp
27   
28    ### LOAD NETCDF DATA
29    #filename = "/home/aymeric/Big_Data/psfc.nc"
30    nc = Dataset(filename) 
31    psfc = nc.variables["PSFC"]
32   
33    ### LOOP on TIME
34    ### NB: a same event could be counted several times...
35    shape = np.array(psfc).shape
36    allsizesx = []
37    allsizesy = []
38    depression = []
39    stride = 1 #5
40    for i in range(0,shape[0],stride):
41
42        psfc2d = np.array ( psfc [ i, : , : ] )
43   
44        ############### CRITERION
45        ave = np.mean(psfc2d,dtype=np.float64)  ## dtype otherwise inaccuracy
46
47        #limdp = -0.2 ## on en loupe pas mal
48        #where = np.where(psfc2d - ave < limdp)  ## comme le papier Phoenix
49   
50        std = np.std(psfc2d,dtype=np.float64)   ## dtype otherwise inaccuracy
51        fac = 4.   ## how many sigmas. not too low, otherwise vortices are not caught. 4 good choice.
52                   ## 2.5 clearly too low, 3.5 not too bad, 4 probably good
53        fac = 3.5
54        #fac = 2.5
55        fac = 3.
56        lim = ave - fac*std
57        where = np.where(psfc2d < lim)
58        ############### END CRITERION
59
60        depression = np.append(depression,np.ravel(psfc2d[where])-ave)
61   
62        lab = np.zeros(np.array(psfc2d).shape) ## points to be treated by the minimum_position routine
63        lab[where] = 1.  ## do not treat points close to 'mean' (background) pressure
64
65        draw = False
66        if draw:
67        ##################################################################################
68            vmin = -0.3
69            vmax =  0.0
70            ndiv = 3
71            palette = plt.get_cmap(name="YlGnBu") 
72            what_I_plot = psfc2d-ave
73            zevmin, zevmax = myp.calculate_bounds(what_I_plot,vmin=vmin,vmax=vmax)
74            what_I_plot = myp.bounds(what_I_plot,zevmin,zevmax)
75            zelevels = np.linspace(zevmin,zevmax)
76            fig = plt.figure() 
77            sub = myp.definesubplot(2,fig)
78            plt.subplot(sub) 
79            plt.contourf(what_I_plot,zelevels,cmap=palette) 
80            plt.colorbar(fraction=0.05,pad=0.03,format="%.1f",\
81                           ticks=np.linspace(zevmin,zevmax,ndiv+1),\
82                           extend='both',spacing='proportional')
83            plt.subplot(sub+1)
84            palette = plt.get_cmap(name="binary")
85            plt.contourf(lab,2,cmap=palette)
86            plt.show() 
87        ##################################################################################
88 
89        xx = []
90        yy = []
91        while 1 in lab:
92            p = minimum_position(psfc2d,labels=lab)
93            lab[p] = 0 ## once a minimum has been found in a grid point, do not search here again.
94            if p[0] not in xx: xx.append(p[0]) ## if x coordinate not yet in the list add it
95            if p[1] not in yy: yy.append(p[1]) ## if y coordinate not yet in the list add it
96        xx.sort()
97        yy.sort()
98        ### now xx and yy are sorted arrays containing grid points with pressure minimum
99       
100        ######## DETERMINE SIZE OF STRUCTURES
101        ######## this is rather brute-force...
102        sizex = detsize( xx, res = 10, loga=False, thres=2 )
103        sizey = detsize( yy, res = 10, loga=False, thres=2 )
104        #sizex = detsize( xx, res = 10, loga=False, thres=3 )
105        #sizey = detsize( yy, res = 10, loga=False, thres=3 )
106        ###
107        #if ( mym.max(sizex) > mym.max(sizey) ): sizey = sizex  ### un peu limite dans certains cas
108        if (len(sizex) > len(sizey))     : sizey = sizex        ### plus fidele mais petit souci lorsque PBC
109        elif (len(sizex) == len(sizey))  : 
110          if ( mym.max(sizex) > mym.max(sizey) ): sizey = sizex
111          else                                  : sizex = sizey
112        else                            : sizex = sizey
113        allsizesx = np.append(allsizesx,sizex)
114        allsizesy = np.append(allsizesy,sizey)
115        print i, ' on ', shape[0], ' caught ', len(sizex), ' vortices ', sizex
116        ########
117 
118    allsizesx.sort()
119    allsizesy.sort()
120   
121    return allsizesx, allsizesy, depression
122
123#########################################################################
124#########################################################################
125
126import matplotlib.pyplot as plt
127import pickle
128import numpy as np
129import matplotlib.mlab as mlab
130import mymath as mym
131import myplot as myp
132
133import plfit
134import plplot
135import randht
136import plpva
137
138save = True
139save = False
140pression = False
141pression = True
142
143if save:
144    allsizesx, allsizesy, depression = getsize("/home/aymeric/Big_Data/psfc.nc")
145    ### sauvegarde texte pour inspection
146    mym.writeascii(allsizesx,'allsizex.txt')
147    mym.writeascii(allsizesy,'allsizey.txt')
148    mym.writeascii(depression,'alldepression.txt')
149    ### sauvegarde binaire pour utilisation python
150    myfile = open('allsizex.bin', 'wb')
151    pickle.dump(allsizesx, myfile)
152    myfile.close()
153    myfile = open('allsizey.bin', 'wb')
154    pickle.dump(allsizesy, myfile)
155    myfile.close()
156    myfile = open('alldepression.bin', 'wb')
157    pickle.dump(depression, myfile)
158    myfile.close()
159
160### load files
161myfile = open('allsizex.bin', 'r')
162allsizesx = pickle.load(myfile)
163myfile = open('allsizey.bin', 'r')
164allsizesy = pickle.load(myfile)
165myfile = open('alldepression.bin', 'r')
166depression = pickle.load(myfile)
167depression = np.array(abs(depression))#*1000.
168
169### sizes
170#plothist = np.append(allsizesx,allsizesy)
171plothist = allsizesx
172if pression: plothist = depression
173plothist.sort()
174print 'mean ', np.mean(plothist,dtype=np.float64) 
175print 'std ', np.std(plothist,dtype=np.float64)
176print 'max ', np.max(plothist)
177print 'min ', np.min(plothist)
178print 'len ', len(plothist)
179
180
181### MAKE BINS
182nbins = 100
183zebins = [2.0]
184#nbins = 8
185#zebins = [19.0]
186#nbins = 15
187#zebins = [11.] ##12 non mais donne un peu la meme chose
188#zebins = [20.] ##20 non car trop pres du premier
189nbins = 100
190zebins = [2./np.sqrt(2.)]  ## ne pas tomber sur une dizaine ronde
191nbins = 200
192
193if pression: zebins = [0.3]
194
195for i in range(0,nbins):  zebins.append(zebins[i]*np.sqrt(2))
196zebins = np.array(zebins)
197#### select reasonable bins for DD
198if not pression:
199    zebins = zebins [ zebins > 15. ] 
200    zebins = zebins [ zebins < 1000. ]
201else:
202    zebins = zebins [ zebins < 10. ]
203print 'corrected bins ',zebins
204
205#### HISTOGRAM
206plt.figure(1)
207plt.hist(    plothist,\
208             log=True,\
209             bins=zebins,\
210#             cumulative=-1,\
211             normed=True,\
212        )
213plt.xscale('log')
214if pression:    plt.xlabel('Pressure (Pa)')
215else:           plt.xlabel('Diameter (m)')
216plt.ylabel('Population (normalized)')
217if pression: prefix="p"
218else:        prefix=""
219myp.makeplotres(prefix+"histogram",res=200,disp=False)
220plt.close(1)
221
222### COMPARED HISTOGRAMS
223### --- FIT WITH POWER LAW
224if pression: [alpha, xmin, L] = plfit.plfit(plothist,'xmin',0.3)
225else:        [alpha, xmin, L] = plfit.plfit(plothist,'limit',20.)
226print 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)
243plt.figure(2)
244### --- POWER LAW (factor does not really matter)
245power = (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
247print 'mean ', np.mean(power,dtype=np.float64)
248### --- EXPONENTIAL LAW
249expo = randht.randht(10000,'exponential',1./(np.mean(power,dtype=np.float64)*1.00))
250print 'mean ', np.mean(expo,dtype=np.float64)
251### --- PLOT
252plt.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        )
259plt.legend()
260plt.xscale('log')
261if pression:    plt.xlabel('Pressure (Pa)')
262else:           plt.xlabel('Diameter (m)')
263plt.ylabel('Population (normalized)')
264myp.makeplotres(prefix+"comparison",res=200,disp=False)
265plt.close(2)
266
267########################
268########################
269zebins = [30.,42.,60.,84.,120.,170.,240.,340.]
270plothist = []
271plothist = np.append(plothist,30 *np.ones(306))
272plothist = np.append(plothist,42 *np.ones(58) )
273plothist = np.append(plothist,60 *np.ones(66) )
274plothist = np.append(plothist,84 *np.ones(41) )
275plothist = np.append(plothist,120*np.ones(19) )
276plothist = np.append(plothist,170*np.ones(9)  )
277plothist = np.append(plothist,240*np.ones(2)  )
278plothist = 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
290plt.figure(3)
291[alpha, xmin, L] = plfit.plfit(plothist,'xmin',30)#50.)
292print alpha,xmin
293#a = plpva.plpva(plothist,30,'xmin',30)
294h = plplot.plplot(plothist,xmin,alpha)
295plt.loglog(h[0], h[1], 'k--',linewidth=2)
296plt.hist(    plothist,\
297             log=True,\
298             bins=zebins,\
299#             cumulative=-1,\
300             normed=True,\
301        )
302plt.xscale('log')
303plt.xlabel('Pressure (micro Pa)')
304plt.ylabel('Population (normalized)')
305myp.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)
Note: See TracBrowser for help on using the repository browser.