source: issm/trunk-jpl/src/py3/miscellaneous/prctile_issm.py@ 23677

Last change on this file since 23677 was 23677, checked in by bdef, 6 years ago

CHG: adding missing directories and cleaning code

File size: 1.7 KB
Line 
1import numpy as np
2from scipy.interpolate import interp1d
3
4#
5# wrapper for prctile to avoid using the matlab statistics toolbox.
6#
7def prctile_issm(x,p,dim):
8
9 try:
10 raise RuntimeError('hello world')
11
12 #numpy has no interpolation method that matches matlab's percentile function
13 #y = np.percentile(x,p,dim,interpolation='higher')
14 except:
15 if len(np.shape(x)) > 2:
16 raise RuntimeError('Number of dimensions #d not implemented.'+str(len(np.shape(x))))
17
18 # presumably at least 1 input value has been given
19 # np.shape(integer) -> (), must be at least (1,)
20 psize=np.shape(p) or (1,)
21 if len(psize) > 1 and np.size(p,1)>1:
22 p=p.T
23
24 xsize=np.shape(x) or (1,)
25 if dim==2:
26 x=x.T
27
28 # check for any NaN in any columns
29 if not np.isnan(x).any():
30 x=np.sort(x,axis=0)
31 n=np.size(x,0)
32
33 # branch based on number of elements
34 if n>1:
35 # set up percent values and interpolate
36 xi=[((i+0.5)*100/n) for i in range(n)]
37 # scipy's interp1d returns a function
38 y=interp1d(xi,x,axis=dim,bounds_error=False)
39 y=y(p)
40
41 # fill in high and low values outside of interp range
42 if p>xi[n-1]:
43 y=np.tile(x[n-1,:],1)
44 if p<xi[0]:
45 y=np.tile(x[0,:],1)
46
47 # if one value, just copy it
48 elif n==1:
49 y=np.tile(x[0,:],(len(p),1))
50
51 # if no values, use NaN
52 else:
53 y=np.tile(float('NaN'),(size(p,0),size(x,0)))
54 else:
55 # must loop over columns, since number of elements could be different
56 y=np.zeros((np.size(p,0),np.size(x,1)))
57 for j in range(np.size(x,1)):
58 # remove any NaN and recursively call column
59 y[:,j]=prctile_issm(x[np.where(not np.isnan(x[:,j]),j)],p)
60
61 if (np.min(xsize)==1 and len(xsize) > 1 and xsize[dim]>1 and len(p) > 1 and psize[1]>1) or (np.min(xsize)> 1 and dim==2):
62 y=y.T
63
64 return y
65
Note: See TracBrowser for help on using the repository browser.