source: trunk/UTIL/PYTHON/powerlaw/ddhist.py @ 1242

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

PYTHON. updated analysis tools for dust devil analysis.

  • Property svn:executable set to *
File size: 5.6 KB
Line 
1#! /usr/bin/env python
2import matplotlib.pyplot as mpl
3import ppplot
4import numpy as np
5import scipy.optimize as sciopt
6
7# -- functions for fitting
8# -- http://wiki.scipy.org/Cookbook/FittingData
9# power law
10def fitfunc(x,a,b): return a*(x**(-b))
11# power law + constant
12def fitfunc3(x,a,b,c): return a*(x**(-b)) + c * (x**(-0.5))
13# exponential law
14def fitfunc2(x,a,b): return a*np.exp(-b*x)
15
16################################################################################
17### HISTODD
18### namefile: text file to be analyzed
19### drop: look at size (False) or pressure drop (True)
20### typefit: use fitfunc above 1, 2, or 3
21### nbins: bins (we expect fit do not depend too much on this -- to be checked)
22### limrest: restrict limit (multiple of dx) -- greater equal
23### addtitle: add a name for the examined case
24################################################################################
25def histodd(namefile,drop=False,typefit=1,nbins=12,limrest=4,addtitle=""):
26
27    # width adapted to number of bins
28    widthbin = {7:3.,10:2.5,12:2.2,15:2.0,20:1.75,30:1.5,50:1.2}
29    www = widthbin[nbins]
30   
31    # load data
32    data = np.loadtxt(namefile,delimiter=";")
33    t = data[:,0] ; s = data[:,1] ; d = data[:,2]
34    i = data[:,3] ; j = data[:,4] # int?
35   
36    # a way to guess resolution
37    dx = np.min(s)/2.
38   
39    # choose a variable
40    if drop: var = d
41    else: var = s
42   
43    # restrictions
44    restrict = (s > 0) # initialization (True everywhere)
45    restrict = restrict*(s >= limrest*dx) # remove lowest sizes (detection limit)
46    restrict = restrict*(np.abs(i-j) <= 6.*dx) # condition sur i,j (width,height) pour ~round shape
47    #restrict = restrict*(d > 0.9) # limit on drop for size
48                                   # (casse la power law? seulement si keep smaller devils)
49    #restrict = restrict*(d > 0.5)
50    #restrict = restrict*(d > 0.3)
51    poum=False
52    if poum:
53      out = var[np.logical_not(restrict)]
54      outi = i[np.logical_not(restrict)]
55      outj = j[np.logical_not(restrict)]
56      print out, outi, outj
57      print out.size
58    var = var[restrict]
59   
60    ## define bins
61    zebins = [np.min(var)]
62    for i in range(0,nbins):  zebins.append(zebins[i]*(www**0.5))
63    zebins = np.array(zebins)
64    middle = 0.5*(zebins[1:] + zebins[:-1])
65    binwidth = zebins[1:] - zebins[:-1]
66    total = var.shape[0]
67   
68    # plot histogram
69    yeah = mpl.hist(var,log=True,bins=zebins,normed=True,color='white') ; mpl.xscale('log')
70    #yeah = mpl.hist(var,bins=zebins,normed=True,color='white')
71   
72    # add error bars
73    incertitude_nvortex = 10.
74    if not drop:
75      err = incertitude_nvortex/(yeah[0]*binwidth*total+0.0001)
76      ind = err < 1000. ; err = err[ind] ; y = yeah[0][ind] ; x = middle[ind]
77      err = y*err
78      mpl.errorbar(x,y,yerr=[err,err],fmt='k.')
79   
80    ## print info
81    #print "min %5.2e // max %5.2e" % (np.min(var),np.max(var))
82    #for iii in range(len(zebins)-1):
83    #    this = zebins[iii] ; next = zebins[iii+1]
84    #    print "%5.2e in [%5.0f %5.0f] %5.0f" % (yeah[0][iii],this,next,np.abs(next-this))
85   
86    # fitting function to superimpose
87    if typefit == 1: xx = sciopt.curve_fit(fitfunc, middle, yeah[0])
88    elif typefit == 2: xx = sciopt.curve_fit(fitfunc2, middle, yeah[0])
89    elif typefit == 3: xx = sciopt.curve_fit(fitfunc3, middle, yeah[0])
90    print "exponent",xx[0][1],"variance %",100.*xx[1][1][1]/xx[0][1]
91   
92    # label
93    lablab = r"$\alpha=$%4.1f"%(xx[0][1])
94    titi = addtitle+"LES "+str(int(dx))+"m. "+str(total)+" detected vortices"
95   
96    # plot obtained fit along with actual points
97    if typefit == 1: func = fitfunc(middle,xx[0][0],xx[0][1])
98    elif typefit == 2: func = fitfunc2(middle,xx[0][0],xx[0][1])
99    elif typefit == 3: func = fitfunc3(middle,xx[0][0],xx[0][1],xx[0][2]) 
100    func[func<0]=np.nan
101    ind = yeah[0]>0
102    mpl.plot(middle[ind],yeah[0][ind],'k.')
103    mpl.plot(middle[ind],func[ind],'r-',label=lablab)
104    mpl.plot(middle[ind],func[ind],'r.')
105   
106    # display bin limits
107    tata = '[bins:'
108    yorgl = ind[np.where(ind)].size + 1 # to add the last limit
109    for el in zebins[0:yorgl]:
110       tata = tata + "%0.f "%(el)
111    tata=tata+']'
112   
113    # print fit vs. actual populations
114    fit = func*binwidth*total
115    pop = yeah[0]*binwidth*total
116    for iii in range(len(fit)):
117        if fit[iii] > 0.99 or pop[iii] != 0:
118            yorgl = 100.*np.abs(fit[iii]-pop[iii])/fit[iii]
119            yargl = 100.*incertitude_nvortex/fit[iii]
120            print "fit %4.0f real %4.0f pc %3.0f ipc %3.0f" % (fit[iii],pop[iii],yorgl,yargl)
121   
122    # plot settings
123    ax = mpl.gca() ; ax.set_xbound(lower=np.min(zebins),upper=np.max(zebins))
124    if drop: 
125        mpl.xlabel("Pressure drop (Pa)")
126        ax.set_xbound(lower=1.e-1,upper=10.)
127    else: 
128        mpl.xlabel("Vortex size (m)")
129        #ax.set_xbound(lower=30.,upper=3000.)
130        ax.set_xbound(lower=30.,upper=1000.)
131        ax.set_ybound(lower=5.e-6,upper=5.e-2)
132    mpl.ylabel('Population density $n / N w_{bin}$')
133    #mpl.title(titi+'\n '+tata)
134    mpl.title(titi)
135    mpl.legend(loc="upper right",fancybox=True)
136       
137    # show plot and end
138    mpl.show()
139
140#################################################################################
141#################################################################################
142#################################################################################
143#
144### UNCOMMENT
145###import plfit,plpva,plplot
146#
147##[alpha, xmin, L] = plfit.plfit(var,'xmin',0.3)
148#[alpha, xmin, L] = plfit.plfit(var)
149#print alpha,xmin
150#
151##a = plpva.plpva(var,0.75,'xmin',0.75)
152##print a
153#
154#
155#h = plplot.plplot(var,xmin,alpha)
156#
157#ppplot.save(mode="png")
158#
159##mpl.loglog(h[0], h[1], 'k--',linewidth=2)
160#
161##mpl.show()
162#
163#
164
Note: See TracBrowser for help on using the repository browser.