source: trunk/UTIL/PYTHON/powerlaw/previous_tests/find_devils.py @ 1242

Last change on this file since 1242 was 1053, checked in by aslmd, 11 years ago

UTIL PYTHON. tools to study dust devils in LES.

  • Property svn:executable set to *
File size: 9.6 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 scipy import ndimage
25    from netCDF4 import Dataset
26    import matplotlib.pyplot as plt
27    import myplot as myp
28   
29    ### LOAD NETCDF DATA
30    nc = Dataset(filename) 
31    psfc = nc.variables["PSFC"]
32    print "yeah"
33   
34    ### LOOP on TIME
35    ### NB: a same event could be counted several times...
36    shape = np.array(psfc).shape
37    allsizesx = []
38    allsizesy = []
39    depression = []
40    stride = 1 #5
41    stride = 20
42    #stride = 50
43    stride = 100
44    start = 0
45    start = stride
46    for i in range(start,shape[0],stride):
47
48        psfc2d = np.array ( psfc [ i, : , : ] )
49   
50        ############### CRITERION
51        ave = np.mean(psfc2d,dtype=np.float64)  ## dtype otherwise inaccuracy
52
53        #limdp = -0.2 ## on en loupe pas mal
54        #where = np.where(psfc2d - ave < limdp)  ## comme le papier Phoenix
55   
56        std = np.std(psfc2d,dtype=np.float64)   ## dtype otherwise inaccuracy
57        fac = 4.   ## how many sigmas. not too low, otherwise vortices are not caught. 4 good choice.
58                   ## 2.5 clearly too low, 3.5 not too bad, 4 probably good
59        fac = 3.5
60        fac = 3.2
61        ##fac = 2.5
62        #fac = 3. ## final choice
63        #fac = 2.5
64        lim = ave - fac*std
65        where = np.where(psfc2d < lim)
66        ############### END CRITERION
67
68        depression = np.append(depression,np.ravel(psfc2d[where])-ave)
69   
70        ## lab is 0 or 1
71        lab = np.zeros(np.array(psfc2d).shape) ## points to be treated by the minimum_position routine
72        lab[where] = 1.  ## do not treat points close to 'mean' (background) pressure
73 
74        xx = []
75        yy = []
76        while 1 in lab:
77            p = minimum_position(psfc2d,labels=lab)
78            lab[p] = 0 ## once a minimum has been found in a grid point, do not search here again.
79            if p[0] not in xx: xx.append(p[0]) ## if x coordinate not yet in the list add it
80            if p[1] not in yy: yy.append(p[1]) ## if y coordinate not yet in the list add it
81        xx.sort()
82        yy.sort()
83        ### now xx and yy are sorted arrays containing grid points with pressure minimum
84       
85        ######## DETERMINE SIZE OF STRUCTURES
86        ######## this is rather brute-force...
87        sizex = detsize( xx, res = 10, loga=False, thres=2 )
88        sizey = detsize( yy, res = 10, loga=False, thres=2 )
89        #sizex = detsize( xx, res = 10, loga=False, thres=3 )
90        #sizey = detsize( yy, res = 10, loga=False, thres=3 )
91        sizex = detsize( xx, res = 15, loga=False, thres=2 )
92        sizey = detsize( yy, res = 15, loga=False, thres=2 )
93        ###
94        print sizex, sizey
95        #if ( mym.max(sizex) > mym.max(sizey) ): sizey = sizex  ### un peu limite dans certains cas
96        if (len(sizex) > len(sizey))     : sizey = sizex        ### plus fidele mais petit souci lorsque PBC
97        elif (len(sizex) == len(sizey))  : 
98          if ( mym.max(sizex) > mym.max(sizey) ): sizey = sizex
99          else                                  : sizex = sizey
100        else                            : sizex = sizey
101        allsizesx = np.append(allsizesx,sizex)
102        allsizesy = np.append(allsizesy,sizey)
103        print i, ' on ', shape[0], ' caught ', len(sizex), ' vortices ', sizex
104        ########
105 
106    allsizesx.sort()
107    allsizesy.sort()
108   
109    return allsizesx, allsizesy, depression
110
111#########################################################################
112#########################################################################
113
114import matplotlib.pyplot as plt
115import pickle
116import numpy as np
117import matplotlib.mlab as mlab
118import mymath as mym
119import myplot as myp
120
121import plfit
122import plplot
123import randht
124import plpva
125
126save = True
127#save = False
128pression = False
129pression = True
130
131filename = "/home/aymeric/Big_Data/psfc_f18.nc"
132
133if save:
134    ### getsize
135    allsizesx, allsizesy, depression = getsize(filename)
136    ### sauvegarde texte pour inspection
137    mym.writeascii(allsizesx,'allsizex.txt')
138    mym.writeascii(allsizesy,'allsizey.txt')
139    mym.writeascii(depression,'alldepression.txt')
140    ### sauvegarde binaire pour utilisation python
141    myfile = open('allsizex.bin', 'wb') ; pickle.dump(allsizesx, myfile) ; myfile.close()
142    myfile = open('allsizey.bin', 'wb') ; pickle.dump(allsizesy, myfile) ; myfile.close()
143    myfile = open('alldepression.bin', 'wb') ; pickle.dump(depression, myfile) ; myfile.close()
144
145### load files
146myfile = open('allsizex.bin', 'r')
147allsizesx = pickle.load(myfile)
148myfile = open('allsizey.bin', 'r')
149allsizesy = pickle.load(myfile)
150myfile = open('alldepression.bin', 'r')
151depression = pickle.load(myfile)
152depression = np.array(abs(depression))#*1000.
153
154### sizes
155#plothist = np.append(allsizesx,allsizesy)
156plothist = allsizesx
157if pression: plothist = depression
158plothist.sort()
159print 'mean ', np.mean(plothist,dtype=np.float64) 
160print 'std ', np.std(plothist,dtype=np.float64)
161print 'max ', np.max(plothist)
162print 'min ', np.min(plothist)
163print 'len ', len(plothist)
164
165
166### MAKE BINS
167nbins = 100
168zebins = [2.0]
169#nbins = 8
170#zebins = [19.0]
171#nbins = 15
172#zebins = [11.] ##12 non mais donne un peu la meme chose
173#zebins = [20.] ##20 non car trop pres du premier
174nbins = 100
175zebins = [2./np.sqrt(2.)]  ## ne pas tomber sur une dizaine ronde
176nbins = 200
177
178if pression: zebins = [0.3]
179
180for i in range(0,nbins):  zebins.append(zebins[i]*np.sqrt(2))
181zebins = np.array(zebins)
182#### select reasonable bins for DD
183if not pression:
184    zebins = zebins [ zebins > 15. ] 
185    #zebins = zebins [ zebins > 20. ]
186    zebins = zebins [ zebins > 25. ]
187    zebins = zebins [ zebins < 1000. ]
188else:
189    zebins = zebins [ zebins < 10. ]
190print 'corrected bins ',zebins
191
192#### HISTOGRAM
193plt.figure(1)
194plt.hist(    plothist,\
195             log=True,\
196             bins=zebins,\
197#             cumulative=-1,\
198             normed=True,\
199        )
200plt.xscale('log')
201if pression:    plt.xlabel('Pressure (Pa)')
202else:           plt.xlabel('Diameter (m)')
203plt.ylabel('Population (normalized)')
204if pression: prefix="p"
205else:        prefix=""
206myp.makeplotres(prefix+"histogram",res=200,disp=False)
207plt.close(1)
208
209### COMPARED HISTOGRAMS
210### --- FIT WITH POWER LAW
211if pression: [alpha, xmin, L] = plfit.plfit(plothist,'xmin',0.3)
212else:        [alpha, xmin, L] = plfit.plfit(plothist,'limit',20.)
213print alpha,xmin
214
215#a = plpva.plpva(plothist,0.75,'xmin',0.75)
216#print a
217
218#### DEUXIEME ROUTINE
219####IL FAUT UTILISER LE DISCRET POUR LA TAILLE !!!
220#if pression:   myplfit = plfit.plfit(plothist,verbose=True,xmin=0.75)
221#else:          myplfit = plfit.plfit(plothist,verbose=True,xmin=20.)
222#myplfit.plotppf()
223#plt.show()
224#exit()
225
226
227#plt.figure(1)
228#h = plplot.plplot(plothist,xmin,alpha)
229#myp.makeplotres(prefix+"fit",res=200,disp=False)
230plt.figure(2)
231### --- POWER LAW (factor does not really matter)
232power = (xmin/2.2)*np.array(randht.randht(10000,'powerlaw',alpha))
233#power = (xmin/2.2)*np.array(randht.randht(10000,'cutoff',alpha,10.)) ##marche pas si trop grand
234print 'mean ', np.mean(power,dtype=np.float64)
235### --- EXPONENTIAL LAW
236expo = randht.randht(10000,'exponential',1./(np.mean(power,dtype=np.float64)*1.00))
237print 'mean ', np.mean(expo,dtype=np.float64)
238### --- PLOT
239plt.hist(    [plothist,power,expo],\
240             label=['LES vortices','Power law '+'{:.1f}'.format(alpha),'Exponential law'],\
241             log=True,\
242             bins=zebins,\
243#            cumulative=-1,\
244             normed=True,\
245        )
246plt.legend()
247plt.xscale('log')
248if pression:    plt.xlabel('Pressure (Pa)')
249else:           plt.xlabel('Diameter (m)')
250plt.ylabel('Population (normalized)')
251myp.makeplotres(prefix+"comparison",res=200,disp=False)
252plt.close(2)
253
254########################
255########################
256zebins = [30.,42.,60.,84.,120.,170.,240.,340.]
257plothist = []
258plothist = np.append(plothist,30 *np.ones(306))
259plothist = np.append(plothist,42 *np.ones(58) )
260plothist = np.append(plothist,60 *np.ones(66) )
261plothist = np.append(plothist,84 *np.ones(41) )
262plothist = np.append(plothist,120*np.ones(19) )
263plothist = np.append(plothist,170*np.ones(9)  )
264plothist = np.append(plothist,240*np.ones(2)  )
265plothist = np.append(plothist,340*np.ones(1)  )
266
267#zebins = [50.,71.,100.,141.,200.,282.,400.]
268#plothist = []
269#plothist = np.append(plothist,50. *np.ones(36))
270#plothist = np.append(plothist,71. *np.ones(18) )
271#plothist = np.append(plothist,100. *np.ones(12) )
272#plothist = np.append(plothist,141. *np.ones(6) )
273#plothist = np.append(plothist,200.*np.ones(4) )
274#plothist = np.append(plothist,282.*np.ones(1)  )
275#plothist = np.append(plothist,400.*np.ones(2)  )
276
277exit()
278
279plt.figure(3)
280[alpha, xmin, L] = plfit.plfit(plothist,'xmin',30)#50.)
281print alpha,xmin
282#a = plpva.plpva(plothist,30,'xmin',30)
283h = plplot.plplot(plothist,xmin,alpha)
284plt.loglog(h[0], h[1], 'k--',linewidth=2)
285plt.hist(    plothist,\
286             log=True,\
287             bins=zebins,\
288#             cumulative=-1,\
289             normed=True,\
290        )
291plt.xscale('log')
292plt.xlabel('Pressure (micro Pa)')
293plt.ylabel('Population (normalized)')
294myp.makeplotres("data",res=200,disp=False)
295
296#plt.figure(4)
297#[alpha, xmin, L] = plfit.plfit(plothist,'xmin',50.) #,'xmin',30.)
298#print alpha,xmin
299#h = plplot.plplot(plothist,xmin,alpha)
300#myp.makeplotres("datafit",res=200,disp=False)
Note: See TracBrowser for help on using the repository browser.