1+ import types
2+ import Numeric
3+ from Numeric import *
4+
5+ __all__ = ['round' ,'any' ,'all' ,'logspace' ,'linspace' ,'fix' ,'mod' ,
6+ 'select' ,'trim_zeros' ,'amax' ,'amin' ,'ptp' ,'cumsum' ,
7+ 'prod' ,'cumprod' ,'diff' ,'angle' ,'unwrap' ,'sort_complex' ]
8+
9+ round = Numeric .around
10+ any = Numeric .sometrue
11+ all = Numeric .alltrue
12+
13+ def logspace (start ,stop ,num = 50 ,endpoint = 1 ):
14+ """ Evenly spaced samples on a logarithmic scale.
15+
16+ Return num evenly spaced samples from 10**start to 10**stop. If
17+ endpoint=1 then last sample is 10**stop.
18+ """
19+ if endpoint :
20+ step = (stop - start )/ float ((num - 1 ))
21+ y = Numeric .arange (0 ,num ) * step + start
22+ else :
23+ step = (stop - start )/ float (num )
24+ y = Numeric .arange (0 ,num ) * step + start
25+ return Numeric .power (10.0 ,y )
26+
27+ def linspace (start ,stop ,num = 50 ,endpoint = 1 ,retstep = 0 ):
28+ """ Evenly spaced samples.
29+
30+ Return num evenly spaced samples from start to stop. If endpoint=1 then
31+ last sample is stop. If retstep is 1 then return the step value used.
32+ """
33+ if endpoint :
34+ step = (stop - start )/ float ((num - 1 ))
35+ y = Numeric .arange (0 ,num ) * step + start
36+ else :
37+ step = (stop - start )/ float (num )
38+ y = Numeric .arange (0 ,num ) * step + start
39+ if retstep :
40+ return y , step
41+ else :
42+ return y
43+
44+ def fix (x ):
45+ """ Round x to nearest integer towards zero.
46+ """
47+ x = Numeric .asarray (x )
48+ y = Numeric .floor (x )
49+ return Numeric .where (x < 0 ,y + 1 ,y )
50+
51+ def mod (x ,y ):
52+ """ x - y*floor(x/y)
53+
54+ For numeric arrays, x % y has the same sign as x while
55+ mod(x,y) has the same sign as y.
56+ """
57+ return x - y * Numeric .floor (x * 1.0 / y )
58+
59+ def select (condlist , choicelist , default = 0 ):
60+ """ Returns an array comprised from different elements of choicelist
61+ depending on the list of conditions.
62+
63+ condlist is a list of condition arrays containing ones or zeros
64+
65+ choicelist is a list of choice matrices (of the "same" size as the
66+ arrays in condlist). The result array has the "same" size as the
67+ arrays in choicelist. If condlist is [c0,...,cN-1] then choicelist
68+ must be of length N. The elements of the choicelist can then be
69+ represented as [v0,...,vN-1]. The default choice if none of the
70+ conditions are met is given as the default argument.
71+
72+ The conditions are tested in order and the first one statisfied is
73+ used to select the choice. In other words, the elements of the
74+ output array are found from the following tree (notice the order of
75+ the conditions matters):
76+
77+ if c0: v0
78+ elif c1: v1
79+ elif c2: v2
80+ ...
81+ elif cN-1: vN-1
82+ else: default
83+
84+ Note, that one of the condition arrays must be large enough to handle
85+ the largest array in the choice list.
86+ """
87+ n = len (condlist )
88+ n2 = len (choicelist )
89+ if n2 != n :
90+ raise ValueError , "List of cases, must be same length as the list of conditions."
91+ choicelist .insert (0 ,default )
92+ S = 0
93+ pfac = 1
94+ for k in range (1 ,n + 1 ):
95+ S += k * pfac * asarray (condlist [k - 1 ])
96+ if k < n :
97+ pfac *= (1 - asarray (condlist [k - 1 ]))
98+ # handle special case of a 1-element condition but
99+ # a multi-element choice
100+ if type (S ) in ScalarType or max (asarray (S ).shape )== 1 :
101+ pfac = asarray (1 )
102+ for k in range (n2 + 1 ):
103+ pfac = pfac + asarray (choicelist [k ])
104+ S = S * ones (asarray (pfac ).shape )
105+ return choose (S , tuple (choicelist ))
106+
107+ # Basic operations
108+ def amax (m ,axis = - 1 ):
109+ """Returns the maximum of m along dimension axis.
110+ """
111+ if axis is None :
112+ m = ravel (m )
113+ axis = 0
114+ else :
115+ m = asarray (m )
116+ return maximum .reduce (m ,axis )
117+
118+ def amin (m ,axis = - 1 ):
119+ """Returns the minimum of m along dimension axis.
120+ """
121+ if axis is None :
122+ m = ravel (m )
123+ axis = 0
124+ else :
125+ m = asarray (m )
126+ return minimum .reduce (m ,axis )
127+
128+ # Actually from Basis, but it fits in so naturally here...
129+
130+ def ptp (m ,axis = - 1 ):
131+ """Returns the maximum - minimum along the the given dimension
132+ """
133+ if axis is None :
134+ m = ravel (m )
135+ axis = 0
136+ else :
137+ m = asarray (m )
138+ return amax (m ,axis )- amin (m ,axis )
139+
140+ def cumsum (m ,axis = - 1 ):
141+ """Returns the cumulative sum of the elements along the given axis
142+ """
143+ if axis is None :
144+ m = ravel (m )
145+ axis = 0
146+ else :
147+ m = asarray (m )
148+ return add .accumulate (m ,axis )
149+
150+ def prod (m ,axis = - 1 ):
151+ """Returns the product of the elements along the given axis
152+ """
153+ if axis is None :
154+ m = ravel (m )
155+ axis = 0
156+ else :
157+ m = asarray (m )
158+ return multiply .reduce (m ,axis )
159+
160+ def cumprod (m ,axis = - 1 ):
161+ """Returns the cumulative product of the elments along the given axis
162+ """
163+ if axis is None :
164+ m = ravel (m )
165+ axis = 0
166+ else :
167+ m = asarray (m )
168+ return multiply .accumulate (m ,axis )
169+
170+ def diff (x , n = 1 ,axis = - 1 ):
171+ """Calculates the nth order, discrete difference along given axis.
172+ """
173+ x = asarray (x )
174+ nd = len (x .shape )
175+ slice1 = [slice (None )]* nd
176+ slice2 = [slice (None )]* nd
177+ slice1 [axis ] = slice (1 ,None )
178+ slice2 [axis ] = slice (None ,- 1 )
179+ if n > 1 :
180+ return diff (x [slice1 ]- x [slice2 ], n - 1 , axis = axis )
181+ else :
182+ return x [slice1 ]- x [slice2 ]
183+
184+ def angle (z ,deg = 0 ):
185+ """Return the angle of complex argument z."""
186+ if deg :
187+ fact = 180 / pi
188+ else :
189+ fact = 1.0
190+ z = asarray (z )
191+ if z .typecode () in ['D' ,'F' ]:
192+ zimag = z .imag
193+ zreal = z .real
194+ else :
195+ zimag = 0
196+ zreal = z
197+ return arctan2 (zimag ,zreal ) * fact
198+
199+ def unwrap (p ,discont = pi ,axis = - 1 ):
200+ """unwrap(p,discont=pi,axis=-1)
201+
202+ unwraps radian phase p by changing absolute jumps greater than discont to
203+ their 2*pi complement along the given axis.
204+ """
205+ p = asarray (p )
206+ nd = len (p .shape )
207+ dd = diff (p ,axis = axis )
208+ slice1 = [slice (None ,None )]* nd # full slices
209+ slice1 [axis ] = slice (1 ,None )
210+ ddmod = mod (dd + pi ,2 * pi )- pi
211+ putmask (ddmod ,(ddmod == - pi ) & (dd > 0 ),pi )
212+ ph_correct = ddmod - dd ;
213+ putmask (ph_correct ,abs (dd )< discont ,0 )
214+ up = array (p ,copy = 1 ,typecode = 'd' )
215+ up [slice1 ] = p [slice1 ] + cumsum (ph_correct ,axis )
216+ return up
217+
218+ def sort_complex (a ):
219+ """ Doesn't currently work for integer arrays -- only float or complex.
220+ """
221+ a = asarray (a ,typecode = a .typecode ().upper ())
222+ def complex_cmp (x ,y ):
223+ res = cmp (x .real ,y .real )
224+ if res == 0 :
225+ res = cmp (x .imag ,y .imag )
226+ return res
227+ l = a .tolist ()
228+ l .sort (complex_cmp )
229+ return array (l )
230+
231+ def trim_zeros (filt ,trim = 'fb' ):
232+ """ Trim the leading and trailing zeros from a 1D array.
233+
234+ Example:
235+ >>> import scipy
236+ >>> a = array((0,0,0,1,2,3,2,1,0))
237+ >>> scipy.trim_zeros(a)
238+ array([1, 2, 3, 2, 1])
239+ """
240+ first = 0
241+ if 'f' in trim or 'F' in trim :
242+ for i in filt :
243+ if i != 0. : break
244+ else : first = first + 1
245+ last = len (filt )
246+ if 'b' in trim or 'B' in trim :
247+ for i in filt [::- 1 ]:
248+ if i != 0. : break
249+ else : last = last - 1
250+ return filt [first :last ]
251+
252+ #-----------------------------------------------------------------------------
253+ # Test Routines
254+ #-----------------------------------------------------------------------------
255+
256+ def test (level = 10 ):
257+ from scipy_base .testing import module_test
258+ module_test (__name__ ,__file__ ,level = level )
259+
260+ def test_suite (level = 1 ):
261+ from scipy_base .testing import module_test_suite
262+ return module_test_suite (__name__ ,__file__ ,level = level )
263+
264+ if __name__ == '__main__' :
265+ test ()
0 commit comments