diff options
author | Jarrod Millman <millman@berkeley.edu> | 2008-04-20 11:49:35 +0000 |
---|---|---|
committer | Jarrod Millman <millman@berkeley.edu> | 2008-04-20 11:49:35 +0000 |
commit | 8c663313de36e860bbfea0909de181d330bfdfc7 (patch) | |
tree | a7b5f3585d2b8a2d8307bfb03dd0e449fa732860 /numpy/lib | |
parent | cb7de97f089b67eaacf37ddbebcfb91c292c0ef4 (diff) | |
download | numpy-8c663313de36e860bbfea0909de181d330bfdfc7.tar.gz |
ran reindent in preparation for the 1.1 release
Diffstat (limited to 'numpy/lib')
-rw-r--r-- | numpy/lib/financial.py | 54 | ||||
-rw-r--r-- | numpy/lib/function_base.py | 52 | ||||
-rw-r--r-- | numpy/lib/index_tricks.py | 2 | ||||
-rw-r--r-- | numpy/lib/io.py | 61 | ||||
-rw-r--r-- | numpy/lib/tests/test__datasource.py | 6 | ||||
-rw-r--r-- | numpy/lib/tests/test_function_base.py | 52 | ||||
-rw-r--r-- | numpy/lib/tests/test_io.py | 22 | ||||
-rw-r--r-- | numpy/lib/tests/test_regression.py | 2 | ||||
-rw-r--r-- | numpy/lib/twodim_base.py | 12 | ||||
-rw-r--r-- | numpy/lib/utils.py | 12 |
10 files changed, 137 insertions, 138 deletions
diff --git a/numpy/lib/financial.py b/numpy/lib/financial.py index 5bb4a3af7..2a751281f 100644 --- a/numpy/lib/financial.py +++ b/numpy/lib/financial.py @@ -2,12 +2,12 @@ # patterned after spreadsheet computations. # There is some complexity in each function -# so that the functions behave like ufuncs with +# so that the functions behave like ufuncs with # broadcasting and being able to be called with scalars -# or arrays (or other sequences). +# or arrays (or other sequences). import numpy as np -__all__ = ['fv', 'pmt', 'nper', 'ipmt', 'ppmt', 'pv', 'rate', +__all__ = ['fv', 'pmt', 'nper', 'ipmt', 'ppmt', 'pv', 'rate', 'irr', 'npv', 'mirr'] _when_to_num = {'end':0, 'begin':1, @@ -19,7 +19,7 @@ _when_to_num = {'end':0, 'begin':1, eqstr = """ - nper / (1 + rate*when) \ / nper \ + nper / (1 + rate*when) \ / nper \ fv + pv*(1+rate) + pmt*|-------------------|*| (1+rate) - 1 | = 0 \ rate / \ / @@ -28,23 +28,23 @@ eqstr = """ where (all can be scalars or sequences) Parameters - ---------- - rate : + ---------- + rate : Rate of interest (per period) - nper : + nper : Number of compounding periods - pmt : - Payment + pmt : + Payment pv : Present value fv : - Future value - when : + Future value + when : When payments are due ('begin' (1) or 'end' (0)) - + """ -def _convert_when(when): +def _convert_when(when): try: return _when_to_num[when] except KeyError: @@ -85,19 +85,19 @@ def pmt(rate, nper, pv, fv=0, when='end'): temp = (1+rate)**nper miter = np.broadcast(rate, nper, pv, fv, when) zer = np.zeros(miter.shape) - fact = np.where(rate==zer, nper+zer, (1+rate*when)*(temp-1)/rate+zer) + fact = np.where(rate==zer, nper+zer, (1+rate*when)*(temp-1)/rate+zer) return -(fv + pv*temp) / fact pmt.__doc__ += eqstr + """ Example ------- -What would the monthly payment need to be to pay off a $200,000 loan in 15 +What would the monthly payment need to be to pay off a $200,000 loan in 15 years at an annual interest rate of 7.5%? >>> pmt(0.075/12, 12*15, 200000) -1854.0247200054619 -In order to pay-off (i.e. have a future-value of 0) the $200,000 obtained +In order to pay-off (i.e. have a future-value of 0) the $200,000 obtained today, a monthly payment of $1,854.02 would be required. """ @@ -160,19 +160,19 @@ def pv(rate, nper, pmt, fv=0.0, when='end'): pv.__doc__ += eqstr # Computed with Sage -# (y + (r + 1)^n*x + p*((r + 1)^n - 1)*(r*w + 1)/r)/(n*(r + 1)^(n - 1)*x - p*((r + 1)^n - 1)*(r*w + 1)/r^2 + n*p*(r + 1)^(n - 1)*(r*w + 1)/r + p*((r + 1)^n - 1)*w/r) +# (y + (r + 1)^n*x + p*((r + 1)^n - 1)*(r*w + 1)/r)/(n*(r + 1)^(n - 1)*x - p*((r + 1)^n - 1)*(r*w + 1)/r^2 + n*p*(r + 1)^(n - 1)*(r*w + 1)/r + p*((r + 1)^n - 1)*w/r) def _g_div_gp(r, n, p, x, y, w): t1 = (r+1)**n t2 = (r+1)**(n-1) return (y + t1*x + p*(t1 - 1)*(r*w + 1)/r)/(n*t2*x - p*(t1 - 1)*(r*w + 1)/(r**2) + n*p*t2*(r*w + 1)/r + p*(t1 - 1)*w/r) -# Use Newton's iteration until the change is less than 1e-6 +# Use Newton's iteration until the change is less than 1e-6 # for all values or a maximum of 100 iterations is reached. -# Newton's rule is -# r_{n+1} = r_{n} - g(r_n)/g'(r_n) +# Newton's rule is +# r_{n+1} = r_{n} - g(r_n)/g'(r_n) # where -# g(r) is the formula +# g(r) is the formula # g'(r) is the derivative with respect to r. def rate(nper, pmt, pv, fv, when='end', guess=0.10, tol=1e-6, maxiter=100): """Number of periods found by solving the equation @@ -194,7 +194,7 @@ def rate(nper, pmt, pv, fv, when='end', guess=0.10, tol=1e-6, maxiter=100): else: return rn rate.__doc__ += eqstr - + def irr(values): """Internal Rate of Return @@ -212,7 +212,7 @@ def irr(values): if rate.size == 1: rate = rate.item() return rate - + def npv(rate, values): """Net Present Value @@ -223,15 +223,15 @@ def npv(rate, values): def mirr(values, finance_rate, reinvest_rate): """Modified internal rate of return - + Parameters ---------- values: Cash flows (must contain at least one positive and one negative value) or nan is returned. - finance_rate : + finance_rate : Interest rate paid on the cash flows - reinvest_rate : + reinvest_rate : Interest rate received on the cash flows upon reinvestment """ @@ -240,7 +240,7 @@ def mirr(values, finance_rate, reinvest_rate): neg = values < 0 if not (pos.size > 0 and neg.size > 0): return np.nan - + n = pos.size + neg.size numer = -npv(reinvest_rate, values[pos])*((1+reinvest_rate)**n) denom = npv(finance_rate, values[neg])*(1+finance_rate) diff --git a/numpy/lib/function_base.py b/numpy/lib/function_base.py index e165c2672..4c02d7c7a 100644 --- a/numpy/lib/function_base.py +++ b/numpy/lib/function_base.py @@ -328,49 +328,49 @@ def histogramdd(sample, bins=10, range=None, normed=False, weights=None): def average(a, axis=None, weights=None, returned=False): """Return the weighted average of array a over the given axis. - - + + Parameters ---------- a : array_like Data to be averaged. axis : {None, integer}, optional - Axis along which to average a. If None, averaging is done over the - entire array irrespective of its shape. + Axis along which to average a. If None, averaging is done over the + entire array irrespective of its shape. weights : {None, array_like}, optional - The importance each datum has in the computation of the - average. The weights array can either be 1D, in which case its length - must be the size of a along the given axis, or of the same shape as a. - If weights=None, all data are assumed to have weight equal to one. + The importance each datum has in the computation of the + average. The weights array can either be 1D, in which case its length + must be the size of a along the given axis, or of the same shape as a. + If weights=None, all data are assumed to have weight equal to one. returned :{False, boolean}, optional If True, the tuple (average, sum_of_weights) is returned, - otherwise only the average is returmed. Note that if weights=None, then + otherwise only the average is returmed. Note that if weights=None, then the sum of the weights is also the number of elements averaged over. Returns ------- average, [sum_of_weights] : {array_type, double} - Return the average along the specified axis. When returned is True, - return a tuple with the average as the first element and the sum - of the weights as the second element. The return type is Float if a is + Return the average along the specified axis. When returned is True, + return a tuple with the average as the first element and the sum + of the weights as the second element. The return type is Float if a is of integer type, otherwise it is of the same type as a. sum_of_weights is has the same type as the average. - + Example ------- >>> average(range(1,11), weights=range(10,0,-1)) 4.0 - + Exceptions ---------- ZeroDivisionError - Raised when all weights along axis are zero. See numpy.ma.average for a - version robust to this type of error. + Raised when all weights along axis are zero. See numpy.ma.average for a + version robust to this type of error. TypeError - Raised when the length of 1D weights is not the same as the shape of a - along axis. - + Raised when the length of 1D weights is not the same as the shape of a + along axis. + """ if not isinstance(a, np.matrix) : a = np.asarray(a) @@ -390,7 +390,7 @@ def average(a, axis=None, weights=None, returned=False): raise TypeError, "1D weights expected when shapes of a and weights differ." if wgt.shape[0] != a.shape[axis] : raise ValueError, "Length of weights not compatible with specified axis." - + # setup wgt to broadcast along axis wgt = np.array(wgt, copy=0, ndmin=a.ndim).swapaxes(-1,axis) @@ -681,20 +681,20 @@ except RuntimeError: def interp(x, xp, fp, left=None, right=None): """Return the value of a piecewise-linear function at each value in x. - The piecewise-linear function, f, is defined by the known data-points - fp=f(xp). The xp points must be sorted in increasing order but this is + The piecewise-linear function, f, is defined by the known data-points + fp=f(xp). The xp points must be sorted in increasing order but this is not checked. - - For values of x < xp[0] return the value given by left. If left is None, + + For values of x < xp[0] return the value given by left. If left is None, then return fp[0]. - For values of x > xp[-1] return the value given by right. If right is + For values of x > xp[-1] return the value given by right. If right is None, then return fp[-1]. """ if isinstance(x, (float, int, number)): return compiled_interp([x], xp, fp, left, right).item() else: return compiled_interp(x, xp, fp, left, right) - + def angle(z, deg=0): """Return the angle of the complex argument z. diff --git a/numpy/lib/index_tricks.py b/numpy/lib/index_tricks.py index 22b8ef388..2039d5b5e 100644 --- a/numpy/lib/index_tricks.py +++ b/numpy/lib/index_tricks.py @@ -294,7 +294,7 @@ class AxisConcatenator(object): objs.append(newobj) if not scalar and isinstance(newobj, _nx.ndarray): arraytypes.append(newobj.dtype) - + # Esure that scalars won't up-cast unless warranted final_dtype = find_common_type(arraytypes, scalartypes) if final_dtype is not None: diff --git a/numpy/lib/io.py b/numpy/lib/io.py index 9e61ab2f8..4c7180245 100644 --- a/numpy/lib/io.py +++ b/numpy/lib/io.py @@ -232,37 +232,37 @@ def loadtxt(fname, dtype=float, comments='#', delimiter=None, converters=None, Parameters ---------- - fname : filename or a file handle. + fname : filename or a file handle. Support for gzipped files is automatic, if the filename ends in .gz - dtype : data-type - Data type of the resulting array. If this is a record data-type, the - resulting array will be 1-d and each row will be interpreted as an - element of the array. The number of columns used must match the number + dtype : data-type + Data type of the resulting array. If this is a record data-type, the + resulting array will be 1-d and each row will be interpreted as an + element of the array. The number of columns used must match the number of fields in the data-type in this case. - comments : str + comments : str The character used to indicate the start of a comment in the file. delimiter : str - A string-like character used to separate values in the file. If delimiter + A string-like character used to separate values in the file. If delimiter is unspecified or none, any whitespace string is a separator. converters : {} - A dictionary mapping column number to a function that will convert that - column to a float. Eg, if column 0 is a date string: - converters={0:datestr2num}. Converters can also be used to provide - a default value for missing data: converters={3:lambda s: float(s or 0)}. - + A dictionary mapping column number to a function that will convert that + column to a float. Eg, if column 0 is a date string: + converters={0:datestr2num}. Converters can also be used to provide + a default value for missing data: converters={3:lambda s: float(s or 0)}. + skiprows : int The number of rows from the top to skip. usecols : sequence - A sequence of integer column indexes to extract where 0 is the first + A sequence of integer column indexes to extract where 0 is the first column, eg. usecols=(1,4,5) will extract the 2nd, 5th and 6th columns. unpack : bool - If True, will transpose the matrix allowing you to unpack into named + If True, will transpose the matrix allowing you to unpack into named arguments on the left hand side. Examples @@ -271,8 +271,8 @@ def loadtxt(fname, dtype=float, comments='#', delimiter=None, converters=None, >>> x,y,z = load('somefile.dat', usecols=(3,5,7), unpack=True) >>> r = np.loadtxt('record.dat', dtype={'names':('gender','age','weight'), 'formats': ('S1','i4', 'f4')}) - - SeeAlso: scipy.io.loadmat to read and write matfiles. + + SeeAlso: scipy.io.loadmat to read and write matfiles. """ if _string_like(fname): @@ -332,23 +332,23 @@ def savetxt(fname, X, fmt='%.18e',delimiter=' '): Parameters ---------- fname : filename or a file handle - If the filename ends in .gz, the file is automatically saved in - compressed gzip format. The load() command understands gzipped files + If the filename ends in .gz, the file is automatically saved in + compressed gzip format. The load() command understands gzipped files transparently. X : array or sequence Data to write to file. - fmt : string - A format string %[flags][width][.precision]specifier. See notes below for + fmt : string + A format string %[flags][width][.precision]specifier. See notes below for a description of some common flags and specifiers. delimiter : str Character separating columns. - + Examples -------- >>> savetxt('test.out', x, delimiter=',') # X is an array >>> savetxt('test.out', (x,y,z)) # x,y,z equal sized 1D arrays - >>> savetxt('test.out', x, fmt='%1.4e') # use exponential notation - + >>> savetxt('test.out', x, fmt='%1.4e') # use exponential notation + Notes on fmt ------------ flags: @@ -362,19 +362,19 @@ def savetxt(fname, X, fmt='%.18e',delimiter=' '): For e, E and f specifiers, the number of digits to print after the decimal point. For g and G, the maximum number of significant digits. - For s, the maximum number of characters. + For s, the maximum number of characters. specifiers: c : character d or i : signed decimal integer - e or E : scientific notation with e or E. + e or E : scientific notation with e or E. f : decimal floating point g,G : use the shorter of e,E or f o : signed octal s : string of characters u : unsigned decimal integer x,X : unsigned hexadecimal integer - - This is not an exhaustive specification. + + This is not an exhaustive specification. """ if _string_like(fname): @@ -403,7 +403,7 @@ def savetxt(fname, X, fmt='%.18e',delimiter=' '): import re def fromregex(file, regexp, dtype): """Construct a record array from a text file, using regular-expressions parsing. - + Array is constructed from all matches of the regular expression in the file. Groups in the regular expression are converted to fields. @@ -423,7 +423,7 @@ def fromregex(file, regexp, dtype): >>> f.write("1312 foo\n1534 bar\n 444 qux") >>> f.close() >>> np.fromregex('test.dat', r"(\d+)\s+(...)", [('num', np.int64), ('key', 'S3')]) - array([(1312L, 'foo'), (1534L, 'bar'), (444L, 'qux')], + array([(1312L, 'foo'), (1534L, 'bar'), (444L, 'qux')], dtype=[('num', '<i8'), ('key', '|S3')]) """ @@ -433,7 +433,7 @@ def fromregex(file, regexp, dtype): regexp = re.compile(regexp) if not isinstance(dtype, np.dtype): dtype = np.dtype(dtype) - + seq = regexp.findall(file.read()) if seq and not isinstance(seq[0], tuple): # make sure np.array doesn't interpret strings as binary data @@ -441,4 +441,3 @@ def fromregex(file, regexp, dtype): seq = [(x,) for x in seq] output = np.array(seq, dtype=dtype) return output - diff --git a/numpy/lib/tests/test__datasource.py b/numpy/lib/tests/test__datasource.py index ad3635490..93e77d28c 100644 --- a/numpy/lib/tests/test__datasource.py +++ b/numpy/lib/tests/test__datasource.py @@ -200,7 +200,7 @@ class TestDataSourceAbspath(NumpyTestCase): tmpfilename = os.path.split(tmpfile)[-1] tmp_path = lambda x: os.path.abspath(self.ds.abspath(x)) - + assert tmp_path(valid_httpurl()).startswith(self.tmpdir) assert tmp_path(invalid_httpurl()).startswith(self.tmpdir) assert tmp_path(tmpfile).startswith(self.tmpdir) @@ -208,7 +208,7 @@ class TestDataSourceAbspath(NumpyTestCase): for fn in malicious_files: assert tmp_path(http_path+fn).startswith(self.tmpdir) assert tmp_path(fn).startswith(self.tmpdir) - + def test_windows_os_sep(self): orig_os_sep = os.sep try: @@ -244,7 +244,7 @@ class TestRepositoryAbspath(NumpyTestCase): for fn in malicious_files: assert tmp_path(http_path+fn).startswith(self.tmpdir) assert tmp_path(fn).startswith(self.tmpdir) - + def test_windows_os_sep(self): orig_os_sep = os.sep try: diff --git a/numpy/lib/tests/test_function_base.py b/numpy/lib/tests/test_function_base.py index d1786969d..52c8cb4d0 100644 --- a/numpy/lib/tests/test_function_base.py +++ b/numpy/lib/tests/test_function_base.py @@ -58,36 +58,36 @@ class TestAverage(NumpyTestCase): assert_almost_equal(y5.mean(1), average(y5, 1)) y6 = matrix(rand(5,5)) - assert_array_equal(y6.mean(0), average(y6,0)) - + assert_array_equal(y6.mean(0), average(y6,0)) + def check_weights(self): y = arange(10) w = arange(10) assert_almost_equal(average(y, weights=w), (arange(10)**2).sum()*1./arange(10).sum()) - + y1 = array([[1,2,3],[4,5,6]]) w0 = [1,2] actual = average(y1,weights=w0,axis=0) desired = array([3.,4.,5.]) assert_almost_equal(actual, desired) - - + + w1 = [0,0,1] desired = array([3., 6.]) assert_almost_equal(average(y1, weights=w1, axis=1), desired) # This should raise an error. Can we test for that ? # assert_equal(average(y1, weights=w1), 9./2.) - - + + # 2D Case w2 = [[0,0,1],[0,0,2]] desired = array([3., 6.]) assert_array_equal(average(y1, weights=w2, axis=1), desired) - + assert_equal(average(y1, weights=w2), 5.) - - + + def check_returned(self): y = array([[1,2,3],[4,5,6]]) @@ -97,23 +97,23 @@ class TestAverage(NumpyTestCase): avg, scl = average(y, 0, returned=True) assert_array_equal(scl, array([2.,2.,2.])) - + avg, scl = average(y, 1, returned=True) assert_array_equal(scl, array([3.,3.])) - + # With weights w0 = [1,2] avg, scl = average(y, weights=w0, axis=0, returned=True) assert_array_equal(scl, array([3., 3., 3.])) - + w1 = [1,2,3] avg, scl = average(y, weights=w1, axis=1, returned=True) assert_array_equal(scl, array([6., 6.])) - + w2 = [[0,0,1],[1,2,3]] avg, scl = average(y, weights=w2, axis=1, returned=True) assert_array_equal(scl, array([1.,6.])) - + class TestSelect(NumpyTestCase): def _select(self,cond,values,default=0): @@ -433,7 +433,7 @@ class TestHistogram(NumpyTestCase): (a,b)=histogram(v) #check if the sum of the bins equals the number of samples assert(sum(a,axis=0)==n) - #check that the bin counts are evenly spaced when the data is from a + #check that the bin counts are evenly spaced when the data is from a # linear function (a,b)=histogram(linspace(0,10,100)) assert(all(a==10)) @@ -443,7 +443,7 @@ class TestHistogramdd(NumpyTestCase): x = array([[-.5, .5, 1.5], [-.5, 1.5, 2.5], [-.5, 2.5, .5], \ [.5, .5, 1.5], [.5, 1.5, 2.5], [.5, 2.5, 2.5]]) H, edges = histogramdd(x, (2,3,3), range = [[-1,1], [0,3], [0,3]]) - answer = asarray([[[0,1,0], [0,0,1], [1,0,0]], [[0,1,0], [0,0,1], + answer = asarray([[[0,1,0], [0,0,1], [1,0,0]], [[0,1,0], [0,0,1], [0,0,1]]]) assert_array_equal(H,answer) # Check normalization @@ -451,12 +451,12 @@ class TestHistogramdd(NumpyTestCase): H, edges = histogramdd(x, bins = ed, normed = True) assert(all(H == answer/12.)) # Check that H has the correct shape. - H, edges = histogramdd(x, (2,3,4), range = [[-1,1], [0,3], [0,4]], + H, edges = histogramdd(x, (2,3,4), range = [[-1,1], [0,3], [0,4]], normed=True) - answer = asarray([[[0,1,0,0], [0,0,1,0], [1,0,0,0]], [[0,1,0,0], + answer = asarray([[[0,1,0,0], [0,0,1,0], [1,0,0,0]], [[0,1,0,0], [0,0,1,0], [0,0,1,0]]]) assert_array_almost_equal(H, answer/6., 4) - # Check that a sequence of arrays is accepted and H has the correct + # Check that a sequence of arrays is accepted and H has the correct # shape. z = [squeeze(y) for y in split(x,3,axis=1)] H, edges = histogramdd(z, bins=(4,3,2),range=[[-2,2], [0,3], [0,2]]) @@ -473,7 +473,7 @@ class TestHistogramdd(NumpyTestCase): def check_shape_3d(self): # All possible permutations for bins of different lengths in 3D. - bins = ((5, 4, 6), (6, 4, 5), (5, 6, 4), (4, 6, 5), (6, 5, 4), + bins = ((5, 4, 6), (6, 4, 5), (5, 6, 4), (4, 6, 5), (6, 5, 4), (4, 5, 6)) r = rand(10,3) for b in bins: @@ -482,11 +482,11 @@ class TestHistogramdd(NumpyTestCase): def check_shape_4d(self): # All possible permutations for bins of different lengths in 4D. - bins = ((7, 4, 5, 6), (4, 5, 7, 6), (5, 6, 4, 7), (7, 6, 5, 4), - (5, 7, 6, 4), (4, 6, 7, 5), (6, 5, 7, 4), (7, 5, 4, 6), - (7, 4, 6, 5), (6, 4, 7, 5), (6, 7, 5, 4), (4, 6, 5, 7), - (4, 7, 5, 6), (5, 4, 6, 7), (5, 7, 4, 6), (6, 7, 4, 5), - (6, 5, 4, 7), (4, 7, 6, 5), (4, 5, 6, 7), (7, 6, 4, 5), + bins = ((7, 4, 5, 6), (4, 5, 7, 6), (5, 6, 4, 7), (7, 6, 5, 4), + (5, 7, 6, 4), (4, 6, 7, 5), (6, 5, 7, 4), (7, 5, 4, 6), + (7, 4, 6, 5), (6, 4, 7, 5), (6, 7, 5, 4), (4, 6, 5, 7), + (4, 7, 5, 6), (5, 4, 6, 7), (5, 7, 4, 6), (6, 7, 4, 5), + (6, 5, 4, 7), (4, 7, 6, 5), (4, 5, 6, 7), (7, 6, 4, 5), (5, 4, 7, 6), (5, 6, 7, 4), (6, 4, 5, 7), (7, 5, 6, 4)) r = rand(10,4) diff --git a/numpy/lib/tests/test_io.py b/numpy/lib/tests/test_io.py index 9e398cf23..31eceb7f6 100644 --- a/numpy/lib/tests/test_io.py +++ b/numpy/lib/tests/test_io.py @@ -38,8 +38,8 @@ class TestSaveTxt(NumpyTestCase): np.savetxt(c, a, delimiter=',', fmt='%d') c.seek(0) assert_equal(c.readlines(), ['1,2\n', '3,4\n']) - - + + ## def test_format(self): ## a = np.array([(1, 2), (3, 4)]) ## c = StringIO.StringIO() @@ -47,21 +47,21 @@ class TestSaveTxt(NumpyTestCase): ## np.savetxt(c, a, fmt=['%02d', '%3.1f']) ## c.seek(0) ## assert_equal(c.readlines(), ['01 2.0\n', '03 4.0\n']) -## +## ## # A single multiformat string ## c = StringIO.StringIO() ## np.savetxt(c, a, fmt='%02d : %3.1f') ## c.seek(0) ## lines = c.readlines() ## assert_equal(lines, ['01 : 2.0\n', '03 : 4.0\n']) -## +## ## # Specify delimiter, should be overiden ## c = StringIO.StringIO() ## np.savetxt(c, a, fmt='%02d : %3.1f', delimiter=',') ## c.seek(0) ## lines = c.readlines() ## assert_equal(lines, ['01 : 2.0\n', '03 : 4.0\n']) - + class TestLoadTxt(NumpyTestCase): def test_record(self): @@ -122,7 +122,7 @@ class TestLoadTxt(NumpyTestCase): converters={3:lambda s: int(s or -999)}) a = np.array([1,2,3,-999,5], int) assert_array_equal(x, a) - + def test_comments(self): c = StringIO.StringIO() c.write('# comment\n1,2,3,5\n') @@ -131,7 +131,7 @@ class TestLoadTxt(NumpyTestCase): comments='#') a = np.array([1,2,3,5], int) assert_array_equal(x, a) - + def test_skiprows(self): c = StringIO.StringIO() c.write('comment\n1,2,3,5\n') @@ -140,7 +140,7 @@ class TestLoadTxt(NumpyTestCase): skiprows=1) a = np.array([1,2,3,5], int) assert_array_equal(x, a) - + c = StringIO.StringIO() c.write('# comment\n1,2,3,5\n') c.seek(0) @@ -148,7 +148,7 @@ class TestLoadTxt(NumpyTestCase): skiprows=1) a = np.array([1,2,3,5], int) assert_array_equal(x, a) - + def test_usecols(self): a =np.array( [[1,2],[3,4]], float) c = StringIO.StringIO() @@ -156,14 +156,14 @@ class TestLoadTxt(NumpyTestCase): c.seek(0) x = np.loadtxt(c, dtype=float, usecols=(1,)) assert_array_equal(x, a[:,1]) - + a =np.array( [[1,2,3],[3,4,5]], float) c = StringIO.StringIO() np.savetxt(c, a) c.seek(0) x = np.loadtxt(c, dtype=float, usecols=(1,2)) assert_array_equal(x, a[:,1:]) - + class Testfromregex(NumpyTestCase): def test_record(self): diff --git a/numpy/lib/tests/test_regression.py b/numpy/lib/tests/test_regression.py index 2e0b3cfb0..868184b81 100644 --- a/numpy/lib/tests/test_regression.py +++ b/numpy/lib/tests/test_regression.py @@ -28,6 +28,6 @@ class TestRegression(NumpyTestCase): tested = np.polyfit(x, y, 4) assert_array_almost_equal(ref, tested) - + if __name__ == "__main__": NumpyTest().run() diff --git a/numpy/lib/twodim_base.py b/numpy/lib/twodim_base.py index a66e94d65..44082521c 100644 --- a/numpy/lib/twodim_base.py +++ b/numpy/lib/twodim_base.py @@ -83,9 +83,9 @@ def diag(v, k=0): raise ValueError, "Input must be 1- or 2-d." def diagflat(v,k=0): - """Return a 2D array whose k'th diagonal is a flattened v and all other - elements are zero. - + """Return a 2D array whose k'th diagonal is a flattened v and all other + elements are zero. + Examples -------- >>> diagflat([[1,2],[3,4]]]) @@ -93,12 +93,12 @@ def diagflat(v,k=0): [0, 2, 0, 0], [0, 0, 3, 0], [0, 0, 0, 4]]) - + >>> diagflat([1,2], 1) array([[0, 1, 0], - [0, 0, 2], + [0, 0, 2], [0, 0, 0]]) - """ + """ try: wrap = v.__array_wrap__ except AttributeError: diff --git a/numpy/lib/utils.py b/numpy/lib/utils.py index b02ba540f..3f7d22092 100644 --- a/numpy/lib/utils.py +++ b/numpy/lib/utils.py @@ -512,7 +512,7 @@ def lookfor(what, module=None, import_modules=True, regenerate=False): if not whats: return for name, (docstring, kind, index) in cache.iteritems(): - if kind in ('module', 'object'): + if kind in ('module', 'object'): # don't show modules or objects continue ok = True @@ -528,7 +528,7 @@ def lookfor(what, module=None, import_modules=True, regenerate=False): # XXX: this is full Harrison-Stetson heuristics now, # XXX: it probably could be improved - kind_relevance = {'func': 1000, 'class': 1000, + kind_relevance = {'func': 1000, 'class': 1000, 'module': -1000, 'object': -1000} def relevance(name, docstr, kind, index): @@ -597,7 +597,7 @@ def _lookfor_generate_cache(module, import_modules, regenerate): cache : dict {obj_full_name: (docstring, kind, index), ...} Docstring cache for the module, either cached one (regenerate=False) or newly generated. - + """ global _lookfor_caches @@ -623,7 +623,7 @@ def _lookfor_generate_cache(module, import_modules, regenerate): index += 1 kind = "object" - + if inspect.ismodule(item): kind = "module" try: @@ -649,13 +649,13 @@ def _lookfor_generate_cache(module, import_modules, regenerate): stack.append(("%s.%s" % (name, n), v)) elif callable(item): kind = "func" - + doc = inspect.getdoc(item) if doc is not None: cache[name] = (doc, kind, index) return cache - + #----------------------------------------------------------------------------- # The following SafeEval class and company are adapted from Michael Spencer's |