diff options
author | Pauli Virtanen <pav@iki.fi> | 2008-10-28 00:13:44 +0000 |
---|---|---|
committer | Pauli Virtanen <pav@iki.fi> | 2008-10-28 00:13:44 +0000 |
commit | 18594cd9653a865fddfa4cd81f82ab54430be1c9 (patch) | |
tree | 04db708f8a8a3575d129390342ff789ef6f1e170 /numpy/lib | |
parent | 7a70f54f515bb8c586c3967d62731a49217eef95 (diff) | |
download | numpy-18594cd9653a865fddfa4cd81f82ab54430be1c9.tar.gz |
Import documentation from doc wiki (part 2, work-in-progress docstrings, but they are still an improvement)
Diffstat (limited to 'numpy/lib')
-rw-r--r-- | numpy/lib/__init__.py | 148 | ||||
-rw-r--r-- | numpy/lib/_datasource.py | 181 | ||||
-rw-r--r-- | numpy/lib/arraysetops.py | 28 | ||||
-rw-r--r-- | numpy/lib/financial.py | 209 | ||||
-rw-r--r-- | numpy/lib/function_base.py | 432 | ||||
-rw-r--r-- | numpy/lib/getlimits.py | 4 | ||||
-rw-r--r-- | numpy/lib/index_tricks.py | 19 | ||||
-rw-r--r-- | numpy/lib/io.py | 39 | ||||
-rw-r--r-- | numpy/lib/polynomial.py | 123 | ||||
-rw-r--r-- | numpy/lib/shape_base.py | 72 | ||||
-rw-r--r-- | numpy/lib/twodim_base.py | 30 | ||||
-rw-r--r-- | numpy/lib/type_check.py | 100 | ||||
-rw-r--r-- | numpy/lib/ufunclike.py | 85 | ||||
-rw-r--r-- | numpy/lib/utils.py | 55 |
14 files changed, 1228 insertions, 297 deletions
diff --git a/numpy/lib/__init__.py b/numpy/lib/__init__.py index 07f6d5c27..296ca7135 100644 --- a/numpy/lib/__init__.py +++ b/numpy/lib/__init__.py @@ -1,3 +1,151 @@ +""" +Basic functions used by several sub-packages and +useful to have in the main name-space. + +Type Handling +------------- +================ =================== +iscomplexobj Test for complex object, scalar result +isrealobj Test for real object, scalar result +iscomplex Test for complex elements, array result +isreal Test for real elements, array result +imag Imaginary part +real Real part +real_if_close Turns complex number with tiny imaginary part to real +isneginf Tests for negative infinity, array result +isposinf Tests for positive infinity, array result +isnan Tests for nans, array result +isinf Tests for infinity, array result +isfinite Tests for finite numbers, array result +isscalar True if argument is a scalar +nan_to_num Replaces NaN's with 0 and infinities with large numbers +cast Dictionary of functions to force cast to each type +common_type Determine the minimum common type code for a group + of arrays +mintypecode Return minimal allowed common typecode. +================ =================== + +Index Tricks +------------ +================ =================== +mgrid Method which allows easy construction of N-d + 'mesh-grids' +``r_`` Append and construct arrays: turns slice objects into + ranges and concatenates them, for 2d arrays appends rows. +index_exp Konrad Hinsen's index_expression class instance which + can be useful for building complicated slicing syntax. +================ =================== + +Useful Functions +---------------- +================ =================== +select Extension of where to multiple conditions and choices +extract Extract 1d array from flattened array according to mask +insert Insert 1d array of values into Nd array according to mask +linspace Evenly spaced samples in linear space +logspace Evenly spaced samples in logarithmic space +fix Round x to nearest integer towards zero +mod Modulo mod(x,y) = x % y except keeps sign of y +amax Array maximum along axis +amin Array minimum along axis +ptp Array max-min along axis +cumsum Cumulative sum along axis +prod Product of elements along axis +cumprod Cumluative product along axis +diff Discrete differences along axis +angle Returns angle of complex argument +unwrap Unwrap phase along given axis (1-d algorithm) +sort_complex Sort a complex-array (based on real, then imaginary) +trim_zeros Trim the leading and trailing zeros from 1D array. +vectorize A class that wraps a Python function taking scalar + arguments into a generalized function which can handle + arrays of arguments using the broadcast rules of + numerix Python. +================ =================== + +Shape Manipulation +------------------ +================ =================== +squeeze Return a with length-one dimensions removed. +atleast_1d Force arrays to be > 1D +atleast_2d Force arrays to be > 2D +atleast_3d Force arrays to be > 3D +vstack Stack arrays vertically (row on row) +hstack Stack arrays horizontally (column on column) +column_stack Stack 1D arrays as columns into 2D array +dstack Stack arrays depthwise (along third dimension) +split Divide array into a list of sub-arrays +hsplit Split into columns +vsplit Split into rows +dsplit Split along third dimension +================ =================== + +Matrix (2D Array) Manipulations +------------------------------- +================ =================== +fliplr 2D array with columns flipped +flipud 2D array with rows flipped +rot90 Rotate a 2D array a multiple of 90 degrees +eye Return a 2D array with ones down a given diagonal +diag Construct a 2D array from a vector, or return a given + diagonal from a 2D array. +mat Construct a Matrix +bmat Build a Matrix from blocks +================ =================== + +Polynomials +----------- +================ =================== +poly1d A one-dimensional polynomial class +poly Return polynomial coefficients from roots +roots Find roots of polynomial given coefficients +polyint Integrate polynomial +polyder Differentiate polynomial +polyadd Add polynomials +polysub Substract polynomials +polymul Multiply polynomials +polydiv Divide polynomials +polyval Evaluate polynomial at given argument +================ =================== + +Import Tricks +------------- +================ =================== +ppimport Postpone module import until trying to use it +ppimport_attr Postpone module import until trying to use its attribute +ppresolve Import postponed module and return it. +================ =================== + +Machine Arithmetics +------------------- +================ =================== +machar_single Single precision floating point arithmetic parameters +machar_double Double precision floating point arithmetic parameters +================ =================== + +Threading Tricks +---------------- +================ =================== +ParallelExec Execute commands in parallel thread. +================ =================== + +1D Array Set Operations +----------------------- +Set operations for 1D numeric arrays based on sort() function. + +================ =================== +ediff1d Array difference (auxiliary function). +unique1d Unique elements of 1D array. +intersect1d Intersection of 1D arrays with unique elements. +intersect1d_nu Intersection of 1D arrays with any elements. +setxor1d Set exclusive-or of 1D arrays with unique elements. +setmember1d Return an array of shape of ar1 containing 1 where + the elements of ar1 are in ar2 and 0 otherwise. +union1d Union of 1D arrays with unique elements. +setdiff1d Set difference of 1D arrays with unique elements. +================ =================== + +""" from info import __doc__ from numpy.version import version as __version__ diff --git a/numpy/lib/_datasource.py b/numpy/lib/_datasource.py index 7e760b416..0fe594ac3 100644 --- a/numpy/lib/_datasource.py +++ b/numpy/lib/_datasource.py @@ -275,26 +275,28 @@ class DataSource (object): return None def abspath(self, path): - """Return absolute path of ``path`` in the DataSource directory. + """ + Return absolute path of file in the DataSource directory. - If ``path`` is an URL, the ``abspath`` will be either the location + If `path` is an URL, the ``abspath`` will be either the location the file exists locally or the location it would exist when opened using the ``open`` method. The functionality is idential to os.path.abspath. - *Parameters*: - - path : {string} - Can be a local file or a remote URL. - - *Returns*: + Parameters + ---------- + path : string + Can be a local file or a remote URL. + Returns + ------- + out : string Complete path, rooted in the DataSource destination directory. - *See Also*: - - `open` : Method that downloads and opens files. + See Also + -------- + open """ # We do this here to reduce the 'import numpy' initial import time. @@ -332,9 +334,10 @@ class DataSource (object): return path def exists(self, path): - """Test if ``path`` exists. + """ + Test if path exists. - Test if ``path`` exists as (and in this order): + Test if `path` exists as (and in this order): - a local file. - a remote URL that have been downloaded and stored locally in the @@ -342,25 +345,26 @@ class DataSource (object): - a remote URL that has not been downloaded, but is valid and accessible. - *Parameters*: + Parameters + ---------- + path : string + Can be a local file or a remote URL. - path : {string} - Can be a local file or a remote URL. - - *Returns*: + Returns + ------- + out : bool + True if `path` exists. - boolean + See Also + -------- + abspath - *See Also*: - - `abspath` - - *Notes* - - When ``path`` is an URL, ``exist`` will return True if it's either - stored locally in the DataSource directory, or is a valid remote - URL. DataSource does not discriminate between to two, the file - is accessible if it exists in either location. + Notes + ----- + When `path` is an URL, ``exist`` will return True if it's either stored + locally in the DataSource directory, or is a valid remote URL. DataSource + does not discriminate between to two, the file is accessible if it exists + in either location. """ # We import this here because importing urllib2 is slow and @@ -387,21 +391,25 @@ class DataSource (object): return False def open(self, path, mode='r'): - """Open ``path`` with ``mode`` and return the file object. + """ + Open and return file-like object. If ``path`` is an URL, it will be downloaded, stored in the DataSource directory and opened from there. - *Parameters*: + Parameters + ---------- + path : string + Local file path or URL to open + mode : {'r', 'w', 'a'}, optional + Mode to open `path`. Mode 'r' for reading, 'w' for writing, 'a' to + append. Available modes depend on the type of object specified by + `path`. - path : {string} - - mode : {string}, optional - - - *Returns*: - - file object + Returns + ------- + out : file object + File object. """ @@ -476,19 +484,106 @@ class Repository (DataSource): return DataSource._findfile(self, self._fullpath(path)) def abspath(self, path): - """Extend DataSource method to prepend baseurl to ``path``.""" + """ + Return absolute path of file in the Repository directory. + + If `path` is an URL, the ``abspath`` will be either the location + the file exists locally or the location it would exist when opened + using the ``open`` method. + + The functionality is idential to os.path.abspath. + + Parameters + ---------- + path : string + Can be a local file or a remote URL. + + Returns + ------- + out : string + Complete path, rooted in the DataSource destination directory. + + See Also + -------- + open + + """ return DataSource.abspath(self, self._fullpath(path)) def exists(self, path): - """Extend DataSource method to prepend baseurl to ``path``.""" + """ + Test if path exists prepending Repository base URL to path. + + Test if `path` exists as (and in this order): + + - a local file. + - a remote URL that have been downloaded and stored locally in the + DataSource directory. + - a remote URL that has not been downloaded, but is valid and + accessible. + + Parameters + ---------- + path : string + Can be a local file or a remote URL. + + Returns + ------- + out : bool + True if `path` exists. + + See Also + -------- + abspath + + Notes + ----- + When `path` is an URL, ``exist`` will return True if it's either stored + locally in the DataSource directory, or is a valid remote URL. DataSource + does not discriminate between to two, the file is accessible if it exists + in either location. + + """ return DataSource.exists(self, self._fullpath(path)) def open(self, path, mode='r'): - """Extend DataSource method to prepend baseurl to ``path``.""" + """ + Open and return file-like object prepending Repository base URL. + + If `path` is an URL, it will be downloaded, stored in the DataSource + directory and opened from there. + + Parameters + ---------- + path : string + Local file path or URL to open + mode : {'r', 'w', 'a'}, optional + Mode to open `path`. Mode 'r' for reading, 'w' for writing, 'a' to + append. Available modes depend on the type of object specified by + `path`. + + Returns + ------- + out : file object + File object. + + """ return DataSource.open(self, self._fullpath(path), mode) def listdir(self): - '''List files in the source Repository.''' + """ + List files in the source Repository. + + Returns + ------- + files : list of str + List of file names (not containing a directory part). + + Notes + ----- + Does not currently work for remote repositories. + + """ if self._isurl(self._baseurl): raise NotImplementedError, \ "Directory listing of URLs, not supported yet." diff --git a/numpy/lib/arraysetops.py b/numpy/lib/arraysetops.py index 270927321..49a1d3e89 100644 --- a/numpy/lib/arraysetops.py +++ b/numpy/lib/arraysetops.py @@ -79,7 +79,7 @@ def unique1d(ar1, return_index=False, return_inverse=False): Parameters ---------- - ar1 : array-like + ar1 : array_like This array will be flattened if it is not already 1-D. return_index : bool, optional If True, also return the indices against `ar1` that result in the @@ -101,8 +101,8 @@ def unique1d(ar1, return_index=False, return_inverse=False): See Also -------- - numpy.lib.arraysetops : Module with a number of other functions - for performing set operations on arrays. + numpy.lib.arraysetops : Module with a number of other functions + for performing set operations on arrays. Examples -------- @@ -230,14 +230,14 @@ def setxor1d(ar1, ar2): Parameters ---------- - ar1 : array + ar1 : array_like Input array. - ar2 : array + ar2 : array_like Input array. Returns ------- - xor : array + xor : ndarray The values that are only in one, but not both, of the input arrays. See Also @@ -269,15 +269,15 @@ def setmember1d(ar1, ar2): Parameters ---------- - ar1 : array + ar1 : array_like Input array. - ar2 : array + ar2 : array_like Input array. Returns ------- - mask : bool-array - The values ar1[mask] are in ar2. + mask : ndarray, bool + The values `ar1[mask]` are in `ar2`. See Also -------- @@ -325,7 +325,7 @@ def union1d(ar1, ar2): Returns ------- - union : array + union : ndarray Unique union of input arrays. See also @@ -345,14 +345,14 @@ def setdiff1d(ar1, ar2): Parameters ---------- - ar1 : array + ar1 : array_like Input array. - ar2 : array + ar2 : array_like Input comparison array. Returns ------- - difference : array + difference : ndarray The values in ar1 that are not in ar2. See Also diff --git a/numpy/lib/financial.py b/numpy/lib/financial.py index ded809c4d..f53a77631 100644 --- a/numpy/lib/financial.py +++ b/numpy/lib/financial.py @@ -30,26 +30,36 @@ def fv(rate, nper, pmt, pv, when='end'): Parameters ---------- - rate : array-like - Rate of interest (per period) - nper : array-like + rate : scalar or array_like of shape(M, ) + Rate of interest as decimal (not per cent) per period + nper : scalar or array_like of shape(M, ) Number of compounding periods - pmt : array-like + pmt : scalar or array_like of shape(M, ) Payment - pv : array-like + pv : scalar or array_like of shape(M, ) Present value - when : array-like - When payments are due ('begin' (1) or 'end' (0)) + when : {{'begin', 1}, {'end', 0}}, {string, int}, optional + When payments are due ('begin' (1) or 'end' (0)). + Defaults to {'end', 0}. + + Returns + ------- + out : ndarray + Future values. If all input is scalar, returns a scalar float. If + any input is array_like, returns future values for each input element. + If multiple inputs are array_like, they all must have the same shape. Notes ----- The future value is computed by solving the equation:: - fv + pv*(1+rate)**nper + pmt*(1+rate*when)/rate * ((1+rate)**nper - 1) == 0 + fv + + pv*(1+rate)**nper + + pmt*(1 + rate*when)/rate*((1 + rate)**nper - 1) == 0 or, when ``rate == 0``:: - fv + pv + pmt * nper == 0 + fv + pv + pmt * nper == 0 Examples -------- @@ -64,6 +74,13 @@ def fv(rate, nper, pmt, pv, when='end'): available today). Thus, saving $100 a month at 5% annual interest leads to $15,692.93 available to spend in 10 years. + If any input is array_like, returns an array of equal shape. Let's + compare different interest rates from the example above. + + >>> a = np.array((0.05, 0.06, 0.07))/12 + >>> np.fv(a, 10*12, -100, -100) + array([ 15692.92889434, 16569.87435405, 17509.44688102]) + """ when = _convert_when(when) rate, nper, pmt, pv, when = map(np.asarray, [rate, nper, pmt, pv, when]) @@ -75,26 +92,36 @@ def fv(rate, nper, pmt, pv, when='end'): def pmt(rate, nper, pv, fv=0, when='end'): """ - Compute the payment. + Compute the payment against loan principal plus interest. Parameters ---------- - rate : array-like + rate : array_like Rate of interest (per period) - nper : array-like + nper : array_like Number of compounding periods - pv : array-like + pv : array_like Present value - fv : array-like + fv : array_like Future value - when : array-like + when : {{'begin', 1}, {'end', 0}}, {string, int} When payments are due ('begin' (1) or 'end' (0)) + Returns + ------- + out : ndarray + Payment against loan plus interest. If all input is scalar, returns a + scalar float. If any input is array_like, returns payment for each + input element. If multiple inputs are array_like, they all must have + the same shape. + Notes ----- The payment ``pmt`` is computed by solving the equation:: - fv + pv*(1+rate)**nper + pmt*(1+rate*when)/rate * ((1+rate)**nper - 1) == 0 + fv + + pv*(1 + rate)**nper + + pmt*(1 + rate*when)/rate*((1 + rate)**nper - 1) == 0 or, when ``rate == 0``:: @@ -132,9 +159,9 @@ def nper(rate, pmt, pv, fv=0, when='end'): Payment pv : array_like Present value - fv : array_like + fv : array_like, optional Future value - when : array_like + when : {{'begin', 1}, {'end', 0}}, {string, int}, optional When payments are due ('begin' (1) or 'end' (0)) Notes @@ -157,8 +184,8 @@ def nper(rate, pmt, pv, fv=0, when='end'): So, over 64 months would be required to pay off the loan. - The same analysis could be done with several different interest rates and/or - payments and/or total amounts to produce an entire table. + The same analysis could be done with several different interest rates + and/or payments and/or total amounts to produce an entire table. >>> np.nper(*(np.ogrid[0.06/12:0.071/12:0.01/12, -200:-99:100, 6000:7001:1000])) array([[[ 32.58497782, 38.57048452], @@ -182,7 +209,42 @@ def nper(rate, pmt, pv, fv=0, when='end'): def ipmt(rate, per, nper, pv, fv=0.0, when='end'): """ - Not implemented. + Not implemented. Compute the payment portion for loan interest. + + Parameters + ---------- + rate : scalar or array_like of shape(M, ) + Rate of interest as decimal (not per cent) per period + per : scalar or array_like of shape(M, ) + Interest paid against the loan changes during the life or the loan. + The `per` is the payment period to calculate the interest amount. + nper : scalar or array_like of shape(M, ) + Number of compounding periods + pv : scalar or array_like of shape(M, ) + Present value + fv : scalar or array_like of shape(M, ), optional + Future value + when : {{'begin', 1}, {'end', 0}}, {string, int}, optional + When payments are due ('begin' (1) or 'end' (0)). + Defaults to {'end', 0}. + + Returns + ------- + out : ndarray + Interest portion of payment. If all input is scalar, returns a scalar + float. If any input is array_like, returns interest payment for each + input element. If multiple inputs are array_like, they all must have + the same shape. + + See Also + -------- + ppmt, pmt, pv + + Notes + ----- + The total payment is made up of payment against principal plus interest. + + ``pmt = ppmt + ipmt`` """ total = pmt(rate, nper, pv, fv, when) @@ -190,6 +252,30 @@ def ipmt(rate, per, nper, pv, fv=0.0, when='end'): raise NotImplementedError def ppmt(rate, per, nper, pv, fv=0.0, when='end'): + """ + Not implemented. Compute the payment against loan principal. + + Parameters + ---------- + rate : array_like + Rate of interest (per period) + per : array_like, int + Amount paid against the loan changes. The `per` is the period of + interest. + nper : array_like + Number of compounding periods + pv : array_like + Present value + fv : array_like, optional + Future value + when : {{'begin', 1}, {'end', 0}}, {string, int} + When payments are due ('begin' (1) or 'end' (0)) + + See Also + -------- + pmt, pv, ipmt + + """ total = pmt(rate, nper, pv, fv, when) return total - ipmt(rate, per, nper, pv, fv, when) @@ -199,22 +285,29 @@ def pv(rate, nper, pmt, fv=0.0, when='end'): Parameters ---------- - rate : array-like + rate : array_like Rate of interest (per period) - nper : array-like + nper : array_like Number of compounding periods - pmt : array-like + pmt : array_like Payment - fv : array-like + fv : array_like, optional Future value - when : array-like + when : {{'begin', 1}, {'end', 0}}, {string, int}, optional When payments are due ('begin' (1) or 'end' (0)) + Returns + ------- + out : ndarray, float + Present value of a series of payments or investments. + Notes ----- The present value ``pv`` is computed by solving the equation:: - fv + pv*(1+rate)**nper + pmt*(1+rate*when)/rate * ((1+rate)**nper - 1) = 0 + fv + + pv*(1 + rate)**nper + + pmt*(1 + rate*when)/rate*((1 + rate)**nper - 1) = 0 or, when ``rate = 0``:: @@ -258,7 +351,7 @@ def rate(nper, pmt, pv, fv, when='end', guess=0.10, tol=1e-6, maxiter=100): Present value fv : array_like Future value - when : array_like, optional + when : {{'begin', 1}, {'end', 0}}, {string, int}, optional When payments are due ('begin' (1) or 'end' (0)) guess : float, optional Starting guess for solving the rate of interest @@ -296,11 +389,27 @@ def rate(nper, pmt, pv, fv, when='end', guess=0.10, tol=1e-6, maxiter=100): return rn def irr(values): - """Internal Rate of Return + """ + Return the Internal Rate of Return (IRR). + + This is the rate of return that gives a net present value of 0.0. - This is the rate of return that gives a net present value of 0.0 + Parameters + ---------- + values : array_like, shape(N,) + Input cash flows per time period. At least the first value would be + negative to represent the investment in the project. + + Returns + ------- + out : float + Internal Rate of Return for periodic input values. + + Examples + -------- + >>> np.irr([-100, 39, 59, 55, 20]) + 0.2809484211599611 - npv(irr(values), values) == 0.0 """ res = np.roots(values[::-1]) # Find the root(s) between 0 and 1 @@ -314,25 +423,51 @@ def irr(values): return rate def npv(rate, values): - """Net Present Value + """ + Returns the NPV (Net Present Value) of a cash flow series. + + Parameters + ---------- + rate : scalar + The discount rate. + values : array_like, shape(M, ) + The values of the time series of cash flows. Must be the same + increment as the `rate`. + + Returns + ------- + out : float + The NPV of the input cash flow series `values` at the discount `rate`. + + Notes + ----- + Returns the result of: + + .. math :: \\sum_{t=1}^M{\\frac{values_t}{(1+rate)^{t}}} - sum ( values_k / (1+rate)**k, k = 1..n) """ values = np.asarray(values) return (values / (1+rate)**np.arange(1,len(values)+1)).sum(axis=0) def mirr(values, finance_rate, reinvest_rate): - """Modified internal rate of return + """ + Modified internal rate of return. Parameters ---------- - values: + values : array_like Cash flows (must contain at least one positive and one negative value) or nan is returned. - finance_rate : + finance_rate : scalar Interest rate paid on the cash flows - reinvest_rate : + reinvest_rate : scalar Interest rate received on the cash flows upon reinvestment + + Returns + ------- + out : float + Modified internal rate of return + """ values = np.asarray(values) diff --git a/numpy/lib/function_base.py b/numpy/lib/function_base.py index 19037d975..0654fad01 100644 --- a/numpy/lib/function_base.py +++ b/numpy/lib/function_base.py @@ -34,34 +34,35 @@ import numpy as np def linspace(start, stop, num=50, endpoint=True, retstep=False): """ - Return evenly spaced numbers. + Return evenly spaced numbers over a specified interval. - `linspace` returns `num` evenly spaced samples, calculated over the - interval ``[start, stop]``. The endpoint of the interval can optionally - be excluded. + Returns `num` evenly spaced samples, calculated over the + interval [`start`, `stop` ]. + + The endpoint of the interval can optionally be excluded. Parameters ---------- - start : float + start : {float, int} The starting value of the sequence. - stop : float + stop : {float, int} The end value of the sequence, unless `endpoint` is set to False. In that case, the sequence consists of all but the last of ``num + 1`` evenly spaced samples, so that `stop` is excluded. Note that the step size changes when `endpoint` is False. - num : int + num : int, optional Number of samples to generate. Default is 50. - endpoint : bool - If true, `stop` is the last sample. Otherwise, it is not included. + endpoint : bool, optional + If True, `stop` is the last sample. Otherwise, it is not included. Default is True. - retstep : bool + retstep : bool, optional If True, return (`samples`, `step`), where `step` is the spacing between samples. Returns ------- samples : ndarray - `num` equally spaced samples in the closed interval + There are `num` equally spaced samples in the closed interval ``[start, stop]`` or the half-open interval ``[start, stop)`` (depending on whether `endpoint` is True or False). step : float (only if `retstep` is True) @@ -71,8 +72,7 @@ def linspace(start, stop, num=50, endpoint=True, retstep=False): See Also -------- arange : Similiar to `linspace`, but uses a step size (instead of the - number of samples). Note that, when used with a float - endpoint, the endpoint may or may not be included. + number of samples). logspace : Samples uniformly distributed in log space. Examples @@ -409,36 +409,36 @@ def histogramdd(sample, bins=10, range=None, normed=False, weights=None): Parameters ---------- - sample : array-like - Data to histogram passed as a sequence of D arrays of length N, or - as an (N,D) array. + sample : array_like + Data to histogram passed as a sequence of D arrays of length N, or + as an (N,D) array. bins : sequence or int, optional - The bin specification: + The bin specification: - * A sequence of arrays describing the bin edges along each dimension. - * The number of bins for each dimension (nx, ny, ... =bins) - * The number of bins for all dimensions (nx=ny=...=bins). + * A sequence of arrays describing the bin edges along each dimension. + * The number of bins for each dimension (nx, ny, ... =bins) + * The number of bins for all dimensions (nx=ny=...=bins). range : sequence, optional - A sequence of lower and upper bin edges to be used if the edges are - not given explicitely in `bins`. Defaults to the minimum and maximum - values along each dimension. + A sequence of lower and upper bin edges to be used if the edges are + not given explicitely in `bins`. Defaults to the minimum and maximum + values along each dimension. normed : boolean, optional - If False, returns the number of samples in each bin. If True, returns - the bin density, ie, the bin count divided by the bin hypervolume. - weights : array-like (N,), optional - An array of values `w_i` weighing each sample `(x_i, y_i, z_i, ...)`. - Weights are normalized to 1 if normed is True. If normed is False, the - values of the returned histogram are equal to the sum of the weights - belonging to the samples falling into each bin. + If False, returns the number of samples in each bin. If True, returns + the bin density, ie, the bin count divided by the bin hypervolume. + weights : array_like (N,), optional + An array of values `w_i` weighing each sample `(x_i, y_i, z_i, ...)`. + Weights are normalized to 1 if normed is True. If normed is False, the + values of the returned histogram are equal to the sum of the weights + belonging to the samples falling into each bin. Returns ------- - H : array - The multidimensional histogram of sample x. See normed and weights for - the different possible semantics. + H : ndarray + The multidimensional histogram of sample x. See normed and weights for + the different possible semantics. edges : list - A list of D arrays describing the bin edges for each dimension. + A list of D arrays describing the bin edges for each dimension. See Also -------- @@ -572,25 +572,24 @@ def average(a, axis=None, weights=None, returned=False): """ Return the weighted average of array over the specified axis. - Parameters ---------- a : array_like Data to be averaged. - axis : {None, integer}, optional + axis : int, optional Axis along which to average `a`. If `None`, averaging is done over the entire array irrespective of its shape. - weights : {None, array_like}, optional + weights : array_like, optional The importance that each datum has in the computation of the average. - The weights array can either be 1D (in which case its length must be + The weights array can either be 1-D (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`, then all data in `a` are assumed to have a weight equal to one. - returned : {False, boolean}, optional - If `True`, the tuple (`average`, `sum_of_weights`) is returned, - otherwise only the average is returned. Note that if `weights=None`, - `sum_of_weights` is equivalent to the number of elements over which - the average is taken. + returned : bool, optional + Default is `False`. If `True`, the tuple (`average`, `sum_of_weights`) + is returned, otherwise only the average is returned. Note that + if `weights=None`, `sum_of_weights` is equivalent to the number of + elements over which the average is taken. Returns ------- @@ -660,7 +659,64 @@ def average(a, axis=None, weights=None, returned=False): return avg def asarray_chkfinite(a): - """Like asarray, but check that no NaNs or Infs are present. + """ + Convert the input to an array, checking for NaNs or Infs. + + Parameters + ---------- + a : array_like + Input data, in any form that can be converted to an array. This + includes lists, lists of tuples, tuples, tuples of tuples, tuples + of lists and ndarrays. Success requires no NaNs or Infs. + dtype : data-type, optional + By default, the data-type is inferred from the input data. + order : {'C', 'F'}, optional + Whether to use row-major ('C') or column-major ('FORTRAN') memory + representation. Defaults to 'C'. + + Returns + ------- + out : ndarray + Array interpretation of `a`. No copy is performed if the input + is already an ndarray. If `a` is a subclass of ndarray, a base + class ndarray is returned. + + Raises + ------ + ValueError + Raises ValueError if `a` contains NaN (Not a Number) or Inf (Infinity). + + See Also + -------- + asarray : Create and array. + asanyarray : Similar function which passes through subclasses. + ascontiguousarray : Convert input to a contiguous array. + asfarray : Convert input to a floating point ndarray. + asfortranarray : Convert input to an ndarray with column-major + memory order. + fromiter : Create an array from an iterator. + fromfunction : Construct an array by executing a function on grid + positions. + + Examples + -------- + Convert a list into an array. If all elements are finite + ``asarray_chkfinite`` is identical to ``asarray``. + + >>> a = [1, 2] + >>> np.asarray_chkfinite(a) + array([1, 2]) + + Raises ValueError if array_like contains Nans or Infs. + + >>> a = [1, 2, np.inf] + >>> try: + ... np.asarray_chkfinite(a) + ... except ValueError: + ... print 'ValueError' + ... + ValueError + """ a = asarray(a) if (a.dtype.char in typecodes['AllFloat']) \ @@ -821,6 +877,15 @@ def select(condlist, choicelist, default=0): output += [V[m] for V,C in zip(values,cond) if C[m]] or [default] + Examples + -------- + >>> t = np.arange(10) + >>> s = np.arange(10)*100 + >>> condlist = [t == 4, t > 5] + >>> choicelist = [s, t] + >>> np.select(condlist, choicelist) + array([ 0, 0, 0, 0, 400, 0, 6, 7, 8, 9]) + """ n = len(condlist) n2 = len(choicelist) @@ -1155,14 +1220,18 @@ def angle(z, deg=0): z : array_like A complex number or sequence of complex numbers. deg : bool, optional - Return angle in degrees if True, radians if False. Default is False. + Return angle in degrees if True, radians if False (default). Returns ------- angle : {ndarray, scalar} - The angle is defined as counterclockwise from the positive real axis on + The counterclockwise angle from the positive real axis on the complex plane, with dtype as numpy.float64. + See Also + -------- + arctan2 + Examples -------- >>> np.angle([1.0, 1.0j, 1+1j]) # in radians @@ -1233,6 +1302,13 @@ def sort_complex(a): out : complex ndarray Always returns a sorted complex array. + Examples + -------- + >>> np.sort_complex([5, 3, 6, 2, 1]) + array([ 1.+0.j, 2.+0.j, 3.+0.j, 5.+0.j, 6.+0.j]) + >>> np.sort_complex([5 + 2j, 3 - 1j, 6 - 2j, 2 - 3j, 1 - 5j]) + array([ 1.-5.j, 2.-3.j, 3.-1.j, 5.+2.j, 6.-2.j]) + """ b = array(a,copy=True) b.sort() @@ -1360,9 +1436,27 @@ def extract(condition, arr): return _nx.take(ravel(arr), nonzero(ravel(condition))[0]) def place(arr, mask, vals): - """Similar to putmask arr[mask] = vals but the 1D array vals has the - same number of elements as the non-zero values of mask. Inverse of - extract. + """ + Changes elements of an array based on conditional and input values. + + Similar to ``putmask(a, mask, vals)`` but the 1D array `vals` has the + same number of elements as the non-zero values of `mask`. Inverse of + ``extract``. + + Sets `a`.flat[n] = `values`\\[n] for each n where `mask`.flat[n] is true. + + Parameters + ---------- + a : array_like + Array to put data into. + mask : array_like + Boolean mask array. + values : array_like, shape(number of non-zero `mask`, ) + Values to put into `a`. + + See Also + -------- + putmask, put, take """ return _insert(arr, mask, vals) @@ -1401,46 +1495,111 @@ def _nanop(op, fill, a, axis=None): def nansum(a, axis=None): """ - Sum the array along the given axis, treating NaNs as zero. + Return the sum of array elements over a given axis treating + Not a Numbers (NaNs) as zero. Parameters ---------- - a : array-like - Input array. - axis : {int, None}, optional - Axis along which the sum is computed. By default `a` is flattened. + a : array_like + Array containing numbers whose sum is desired. If `a` is not an + array, a conversion is attempted. + axis : int, optional + Axis along which the sum is computed. The default is to compute + the sum of the flattened array. Returns ------- - y : {ndarray, scalar} - The sum ignoring NaNs. + y : ndarray + An array with the same shape as a, with the specified axis removed. + If a is a 0-d array, or if axis is None, a scalar is returned with + the same dtype as `a`. + + See Also + -------- + numpy.sum : Sum across array including Not a Numbers. + isnan : Shows which elements are Not a Number (NaN). + isfinite: Shows which elements are not: Not a Number, positive and + negative infinity + + Notes + ----- + Numpy uses the IEEE Standard for Binary Floating-Point for Arithmetic + (IEEE 754). This means that Not a Number is not equivalent to infinity. + If positive or negative infinity are present the result is positive or + negative infinity. But if both positive and negative infinity are present, + the result is Not A Number (NaN). + + Arithmetic is modular when using integer types (all elements of `a` must + be finite i.e. no elements that are NaNs, positive infinity and negative + infinity because NaNs are floating point types), and no error is raised + on overflow. + Examples -------- - >>> np.nansum([np.nan, 1]) + >>> np.nansum(1) + 1 + >>> np.nansum([1]) + 1 + >>> np.nansum([1, np.nan]) 1.0 >>> a = np.array([[1, 1], [1, np.nan]]) + >>> np.nansum(a) + 3.0 >>> np.nansum(a, axis=0) array([ 2., 1.]) + When positive infinity and negative infinity are present + + >>> np.nansum([1, np.nan, np.inf]) + inf + >>> np.nansum([1, np.nan, np.NINF]) + -inf + >>> np.nansum([1, np.nan, np.inf, np.NINF]) + nan + """ return _nanop(np.sum, 0, a, axis) def nanmin(a, axis=None): """ - Find the minimum along the given axis, ignoring NaNs. + Return the minimum of array elements over the given axis ignoring any NaNs. Parameters ---------- a : array_like - Input array. + Array containing numbers whose sum is desired. If `a` is not + an array, a conversion is attempted. axis : int, optional - Axis along which the minimum is computed. By default `a` is flattened. + Axis along which the minimum is computed.The default is to compute + the minimum of the flattened array. Returns ------- y : {ndarray, scalar} - The minimum ignoring NaNs. + An array with the same shape as `a`, with the specified axis removed. + If `a` is a 0-d array, or if axis is None, a scalar is returned. The + the same dtype as `a` is returned. + + + See Also + -------- + numpy.amin : Minimum across array including any Not a Numbers. + numpy.nanmax : Maximum across array ignoring any Not a Numbers. + isnan : Shows which elements are Not a Number (NaN). + isfinite: Shows which elements are not: Not a Number, positive and + negative infinity + + Notes + ----- + Numpy uses the IEEE Standard for Binary Floating-Point for Arithmetic + (IEEE 754). This means that Not a Number is not equivalent to infinity. + Positive infinity is treated as a very large number and negative infinity + is treated as a very small (i.e. negative) number. + + If the input has a integer type, an integer type is returned unless + the input contains NaNs and infinity. + Examples -------- @@ -1452,34 +1611,65 @@ def nanmin(a, axis=None): >>> np.nanmin(a, axis=1) array([ 1., 3.]) + When positive infinity and negative infinity are present: + + >>> np.nanmin([1, 2, np.nan, np.inf]) + 1.0 + >>> np.nanmin([1, 2, np.nan, np.NINF]) + -inf + """ return _nanop(np.min, np.inf, a, axis) def nanargmin(a, axis=None): """ - Return indices of the minimum values along the given axis of `a`, - ignoring NaNs. + Return indices of the minimum values along an axis, ignoring NaNs. - Refer to `numpy.nanargmax` for detailed documentation. + + See Also + -------- + nanargmax : corresponding function for maxima; see for details. """ return _nanop(np.argmin, np.inf, a, axis) def nanmax(a, axis=None): """ - Find the maximum along the given axis, ignoring NaNs. + Return the maximum of array elements over the given axis ignoring any NaNs. Parameters ---------- - a : array-like - Input array. - axis : {int, None}, optional - Axis along which the maximum is computed. By default `a` is flattened. + a : array_like + Array containing numbers whose maximum is desired. If `a` is not + an array, a conversion is attempted. + axis : int, optional + Axis along which the maximum is computed.The default is to compute + the maximum of the flattened array. Returns ------- - y : {ndarray, scalar} - The maximum ignoring NaNs. + y : ndarray + An array with the same shape as `a`, with the specified axis removed. + If `a` is a 0-d array, or if axis is None, a scalar is returned. The + the same dtype as `a` is returned. + + See Also + -------- + numpy.amax : Maximum across array including any Not a Numbers. + numpy.nanmin : Minimum across array ignoring any Not a Numbers. + isnan : Shows which elements are Not a Number (NaN). + isfinite: Shows which elements are not: Not a Number, positive and + negative infinity + + Notes + ----- + Numpy uses the IEEE Standard for Binary Floating-Point for Arithmetic + (IEEE 754). This means that Not a Number is not equivalent to infinity. + Positive infinity is treated as a very large number and negative infinity + is treated as a very small (i.e. negative) number. + + If the input has a integer type, an integer type is returned unless + the input contains NaNs and infinity. Examples -------- @@ -1491,29 +1681,35 @@ def nanmax(a, axis=None): >>> np.nanmax(a, axis=1) array([ 2., 3.]) + When positive infinity and negative infinity are present: + + >>> np.nanmax([1, 2, np.nan, np.NINF]) + 2.0 + >>> np.nanmax([1, 2, np.nan, np.inf]) + inf + """ return _nanop(np.max, -np.inf, a, axis) def nanargmax(a, axis=None): """ - Return indices of the maximum values over the given axis of 'a', - ignoring NaNs. + Return indices of the maximum values over an axis, ignoring NaNs. Parameters ---------- - a : array-like + a : array_like Input data. axis : int, optional Axis along which to operate. By default flattened input is used. Returns ------- - index_array : {ndarray, int} + index_array : ndarray An array of indices or a single index value. See Also -------- - argmax + argmax, nanargmin Examples -------- @@ -1531,8 +1727,19 @@ def nanargmax(a, axis=None): return _nanop(np.argmax, -np.inf, a, axis) def disp(mesg, device=None, linefeed=True): - """Display a message to the given device (default is sys.stdout) - with or without a linefeed. + """ + Display a message on a device + + Parameters + ---------- + mesg : string + Message to display. + device : device object with 'write' method + Device to write message. If None, defaults to ``sys.stdout`` which is + very similar to ``print``. + linefeed : bool, optional + Option whether to print a line feed or not. Defaults to True. + """ if device is None: import sys @@ -1695,11 +1902,11 @@ def cov(m, y=None, rowvar=1, bias=0): Parameters ---------- - m : array-like - A 1D or 2D array containing multiple variables and observations. + m : array_like + A 1-D or 2-D array containing multiple variables and observations. Each row of `m` represents a variable, and each column a single observation of all those variables. Also see `rowvar` below. - y : array-like, optional + y : array_like, optional An additional set of variables and observations. `y` has the same form as that of `m`. rowvar : int, optional @@ -1790,7 +1997,7 @@ def cov(m, y=None, rowvar=1, bias=0): def corrcoef(x, y=None, rowvar=1, bias=0): """ - Correlation coefficients. + Return correlation coefficients. Please refer to the documentation for `cov` for more detail. The relationship between the correlation coefficient matrix, P, and the @@ -2014,9 +2221,9 @@ def hanning(M): Returns ------- - out : array + out : ndarray, shape(M,) The window, normalized to one (the value one - appears only if the number of samples is odd). + appears only if `M` is odd). See Also -------- @@ -2259,17 +2466,30 @@ def _i0_2(x): def i0(x): """ - Modified Bessel function of the first kind, order 0, :math:`I_0` + Modified Bessel function of the first kind, order 0. + + Usually denoted :math:`I_0`. Parameters ---------- - x : array-like, dtype float or complex + x : array_like, dtype float or complex Argument of the Bessel function. Returns ------- out : ndarray, shape z.shape, dtype z.dtype - The modified Bessel function evaluated for all elements of `x`. + The modified Bessel function evaluated at the elements of `x`. + + See Also + -------- + scipy.special.iv, scipy.special.ive + + References + ---------- + .. [1] M. Abramowitz and I.A. Stegun, "Handbook of Mathematical Functions", + 10th printing, 1964, pp. 374. http://www.math.sfu.ca/~cbm/aands/ + .. [2] Wikipedia, "Bessel function", + http://en.wikipedia.org/wiki/Bessel_function Examples -------- @@ -2361,11 +2581,11 @@ def kaiser(M,beta): References ---------- - .. [1] J. F. Kaiser, "Digital Filters" - Ch 7 in "Systems analysis by - digital computer", Editors: F.F. Kuo and J.F. Kaiser, p 218-285. - John Wiley and Sons, New York, (1966). - .. [2]\tE.R. Kanasewich, "Time Sequence Analysis in Geophysics", The - University of Alberta Press, 1975, pp. 177-178. + .. [1] J. F. Kaiser, "Digital Filters" - Ch 7 in "Systems analysis by + digital computer", Editors: F.F. Kuo and J.F. Kaiser, p 218-285. + John Wiley and Sons, New York, (1966). + .. [2] E.R. Kanasewich, "Time Sequence Analysis in Geophysics", The + University of Alberta Press, 1975, pp. 177-178. .. [3] Wikipedia, "Window function", http://en.wikipedia.org/wiki/Window_function @@ -2483,6 +2703,28 @@ def sinc(x): return sin(y)/y def msort(a): + """ + Return a copy of an array sorted along the first axis. + + Parameters + ---------- + a : array_like + Array to be sorted. + + Returns + ------- + sorted_array : ndarray + Array of the same type and shape as `a`. + + See Also + -------- + sort + + Notes + ----- + ``np.msort(a)`` is equivalent to ``np.sort(a, axis=0)``. + + """ b = array(a,subok=True,copy=True) b.sort(0) return b @@ -2593,7 +2835,7 @@ def trapz(y, x=None, dx=1.0, axis=-1): ---------- y : array_like Input array to integrate. - x : {array_like, None}, optional + x : array_like, optional If `x` is None, then spacing between all `y` elements is 1. dx : scalar, optional If `x` is None, spacing given by `dx` is assumed. @@ -2707,11 +2949,11 @@ def delete(arr, obj, axis=None): Parameters ---------- - arr : array-like + arr : array_like Input array. obj : slice, integer or an array of integers Indicate which sub-arrays to remove. - axis : integer or None + axis : integer, optional The axis along which to delete the subarray defined by `obj`. If `axis` is None, `obj` is applied to the flattened array. diff --git a/numpy/lib/getlimits.py b/numpy/lib/getlimits.py index 4c432c0e4..bc5fbbf5e 100644 --- a/numpy/lib/getlimits.py +++ b/numpy/lib/getlimits.py @@ -22,6 +22,8 @@ _convert_to_float = { class finfo(object): """ + finfo(dtype) + Machine limits for floating point types. Attributes @@ -170,6 +172,8 @@ nexp =%(nexp)6s min= -max class iinfo: """ + iinfo(type) + Machine limits for integer types. Attributes diff --git a/numpy/lib/index_tricks.py b/numpy/lib/index_tricks.py index 02018c87e..3021635dc 100644 --- a/numpy/lib/index_tricks.py +++ b/numpy/lib/index_tricks.py @@ -20,8 +20,6 @@ def unravel_index(x,dims): """ Convert a flat index into an index tuple for an array of given shape. - e.g. for a 2x2 array, unravel_index(2,(2,2)) returns (1,0). - Parameters ---------- x : int @@ -31,25 +29,26 @@ def unravel_index(x,dims): Notes ----- - Since x.flat[p] == x.max() it may be easier to use flattened indexing - than to re-map the index to a tuple. + In the Examples section, since ``arr.flat[x] == arr.max()`` it may be + easier to use flattened indexing than to re-map the index to a tuple. Examples -------- - >>> x = np.ones((5,4)) - >>> x + >>> arr = np.ones((5,4)) + >>> arr array([[ 0, 1, 2, 3], [ 4, 5, 6, 7], [ 8, 9, 10, 11], [12, 13, 14, 15], [16, 17, 18, 19]]) - >>> p = x.argmax() - >>> p + >>> x = arr.argmax() + >>> x 19 - >>> idx = np.unravel_index(p, x.shape) + >>> dims = arr.shape + >>> idx = np.unravel_index(x, dims) >>> idx (4, 3) - >>> x[idx] == x.max() + >>> arr[idx] == arr.max() True """ diff --git a/numpy/lib/io.py b/numpy/lib/io.py index caa790809..deb86fb61 100644 --- a/numpy/lib/io.py +++ b/numpy/lib/io.py @@ -81,36 +81,36 @@ class NpzFile(object): def load(file, memmap=False): """ - Load pickled, ``.npy``, and ``.npz`` binary files. + Load a pickled, ``.npy``, or ``.npz`` binary file. Parameters ---------- file : file-like object or string - The file to read. It must support seek and read methods. + The file to read. It must support ``seek()`` and ``read()`` methods. memmap : bool If True, then memory-map the ``.npy`` file (or unzip the ``.npz`` file - into a temporary directory and memory-map each component). This has no - effect for a pickled file. + into a temporary directory and memory-map each component). This has + no effect for a pickled file. Returns ------- result : array, tuple, dict, etc. Data stored in the file. - - If file contains pickle data, then whatever is stored in the - pickle is returned. - - - If the file is a ``.npy`` file, then an array is returned. - - - If the file is a ``.npz`` file, then a dictionary-like object is - returned, containing {filename: array} key-value pairs, one for - every file in the archive. - Raises ------ IOError If the input file does not exist or cannot be read. + Notes + ----- + - If file contains pickle data, then whatever is stored in the + pickle is returned. + - If the file is a ``.npy`` file, then an array is returned. + - If the file is a ``.npz`` file, then a dictionary-like object is + returned, containing {filename: array} key-value pairs, one for + every file in the archive. + Examples -------- >>> np.save('/tmp/123', np.array([1, 2, 3]) @@ -178,12 +178,23 @@ def save(file, arr): format.write_array(fid, arr) def savez(file, *args, **kwds): - """Save several arrays into an .npz file format which is a zipped-archive + """ + Save several arrays into an .npz file format which is a zipped-archive of arrays If keyword arguments are given, then filenames are taken from the keywords. If arguments are passed in with no keywords, then stored file names are arr_0, arr_1, etc. + + Parameters + ---------- + file : string + File name of .npz file. + args : Arguments + Function arguments. + kwds : Keyword arguments + Keywords. + """ # Import is postponed to here since zipfile depends on gzip, an optional diff --git a/numpy/lib/polynomial.py b/numpy/lib/polynomial.py index 7e3a02107..4a70c9fa3 100644 --- a/numpy/lib/polynomial.py +++ b/numpy/lib/polynomial.py @@ -129,7 +129,7 @@ def roots(p): Parameters ---------- - p : (N,) array_like + p : array_like of shape(M,) Rank-1 array of polynomial co-efficients. Returns @@ -200,7 +200,7 @@ def polyint(p, m=1, k=None): Parameters ---------- - p : poly1d or sequence + p : {array_like, poly1d} Polynomial to differentiate. A sequence is interpreted as polynomial coefficients, see `poly1d`. m : int, optional @@ -523,7 +523,7 @@ def polyfit(x, y, deg, rcond=None, full=False): def polyval(p, x): """ - Evaluate the polynomial p at x. + Evaluate a polynomial at specific values. If p is of length N, this function returns the value: @@ -543,7 +543,7 @@ def polyval(p, x): Returns ------- - values : {array, poly1d} + values : {ndarray, poly1d} If either p or x is an instance of poly1d, then an instance of poly1d is returned, otherwise a 1D array is returned. In the case where x is a poly1d, the result is the composition of the two polynomials, i.e., @@ -577,7 +577,28 @@ def polyval(p, x): return y def polyadd(a1, a2): - """Adds two polynomials represented as sequences + """ + Returns sum of two polynomials. + + Returns sum of polynomials; `a1` + `a2`. Input polynomials are + represented as an array_like sequence of terms or a poly1d object. + + Parameters + ---------- + a1 : {array_like, poly1d} + Polynomial as sequence of terms. + a2 : {array_like, poly1d} + Polynomial as sequence of terms. + + Returns + ------- + out : {ndarray, poly1d} + Array representing the polynomial terms. + + See Also + -------- + polyval, polydiv, polymul, polyadd + """ truepoly = (isinstance(a1, poly1d) or isinstance(a2, poly1d)) a1 = atleast_1d(a1) @@ -596,7 +617,35 @@ def polyadd(a1, a2): return val def polysub(a1, a2): - """Subtracts two polynomials represented as sequences + """ + Returns difference from subtraction of two polynomials input as sequences. + + Returns difference of polynomials; `a1` - `a2`. Input polynomials are + represented as an array_like sequence of terms or a poly1d object. + + Parameters + ---------- + a1 : {array_like, poly1d} + Minuend polynomial as sequence of terms. + a2 : {array_like, poly1d} + Subtrahend polynomial as sequence of terms. + + Returns + ------- + out : {ndarray, poly1d} + Array representing the polynomial terms. + + See Also + -------- + polyval, polydiv, polymul, polyadd + + Examples + -------- + .. math:: (2 x^2 + 10x - 2) - (3 x^2 + 10x -4) = (-x^2 + 2) + + >>> np.polysub([2, 10, -2], [3, 10, -4]) + array([-1, 0, 2]) + """ truepoly = (isinstance(a1, poly1d) or isinstance(a2, poly1d)) a1 = atleast_1d(a1) @@ -616,7 +665,29 @@ def polysub(a1, a2): def polymul(a1, a2): - """Multiplies two polynomials represented as sequences. + """ + Returns product of two polynomials represented as sequences. + + The input arrays specify the polynomial terms in turn with a length equal + to the polynomial degree plus 1. + + Parameters + ---------- + a1 : {array_like, poly1d} + First multiplier polynomial. + a2 : {array_like, poly1d} + Second multiplier polynomial. + + Returns + ------- + out : {ndarray, poly1d} + Product of inputs. + + See Also + -------- + poly, polyadd, polyder, polydiv, polyfit, polyint, polysub, + polyval + """ truepoly = (isinstance(a1, poly1d) or isinstance(a2, poly1d)) a1,a2 = poly1d(a1),poly1d(a2) @@ -626,8 +697,40 @@ def polymul(a1, a2): return val def polydiv(u, v): - """Computes q and r polynomials so that u(s) = q(s)*v(s) + r(s) - and deg r < deg v. + """ + Returns the quotient and remainder of polynomial division. + + The input arrays specify the polynomial terms in turn with a length equal + to the polynomial degree plus 1. + + Parameters + ---------- + u : {array_like, poly1d} + Dividend polynomial. + v : {array_like, poly1d} + Divisor polynomial. + + Returns + ------- + q : ndarray + Polynomial terms of quotient. + r : ndarray + Remainder of polynomial division. + + See Also + -------- + poly, polyadd, polyder, polydiv, polyfit, polyint, polymul, polysub, + polyval + + Examples + -------- + .. math:: \\frac{3x^2 + 5x + 2}{2x + 1} = 1.5x + 1.75, remainder 0.25 + + >>> x = np.array([3.0, 5.0, 2.0]) + >>> y = np.array([2.0, 1.0]) + >>> np.polydiv(x, y) + >>> (array([ 1.5 , 1.75]), array([ 0.25])) + """ truepoly = (isinstance(u, poly1d) or isinstance(u, poly1d)) u = atleast_1d(u) @@ -683,7 +786,7 @@ class poly1d(object): Parameters ---------- c_or_r : array_like - Polynomial coefficients, in decreasing powers. E.g., + Polynomial coefficients, in decreasing powers. For example, ``(1, 2, 3)`` implies :math:`x^2 + 2x + 3`. If `r` is set to True, these coefficients specify the polynomial roots (values where the polynomial evaluate to 0) instead. diff --git a/numpy/lib/shape_base.py b/numpy/lib/shape_base.py index 8f6073bd5..a890a8a2b 100644 --- a/numpy/lib/shape_base.py +++ b/numpy/lib/shape_base.py @@ -12,28 +12,28 @@ def apply_along_axis(func1d,axis,arr,*args): """ Apply function to 1-D slices along the given axis. - Execute `func1d(arr[i],*args)` where `func1d` takes 1-D arrays, `arr` is + Execute `func1d(a[i],*args)` where `func1d` takes 1-D arrays, `a` is the input array, and `i` is an integer that varies in order to apply the - function along the given axis for each 1-D subarray in `arr`. + function along the given axis for each 1-D subarray in `a`. Parameters ---------- func1d : function This function should be able to take 1-D arrays. It is applied to 1-D - slices of `arr` along the specified axis. + slices of `a` along the specified axis. axis : integer Axis along which `func1d` is applied. - arr : ndarray + a : ndarray Input array. args : any Additional arguments to `func1d`. Returns ------- - outarr : ndarray - The output array. The shape of `outarr` depends on the return - value of `func1d`. If it returns arrays with the same shape as the - input arrays it receives, `outarr` has the same shape as `arr`. + out : ndarray + The output array. The shape of `out` is identical to the shape of `a`, + except along the `axis` dimension, whose length is equal to the size + of the return value of `func1d`. See Also -------- @@ -112,28 +112,28 @@ def apply_over_axes(func, a, axes): """ Apply a function repeatedly over multiple axes. - `func` is called as `res = func(a, axis)`, with `axis` the first element - of `axes`. The result `res` of the function call has to have - the same or one less dimension(s) as `a`. If `res` has one less dimension - than `a`, a dimension is then inserted before `axis`. + `func` is called as `res = func(a, axis)`, where `axis` is the first + element of `axes`. The result `res` of the function call must have + either the same dimensions as `a` or one less dimension. If `res` has one + less dimension than `a`, a dimension is inserted before `axis`. The call to `func` is then repeated for each axis in `axes`, with `res` as the first argument. Parameters ---------- func : function - This function should take two arguments, `func(a, axis)`. - arr : ndarray + This function must take two arguments, `func(a, axis)`. + a : ndarray Input array. axes : array_like - Axes over which `func` has to be applied, the elements should be + Axes over which `func` is applied, the elements must be integers. Returns ------- val : ndarray - The output array. The number of dimensions is the same as `a`, - the shape can be different, this depends on whether `func` changes + The output array. The number of dimensions is the same as `a`, but + the shape can be different. This depends on whether `func` changes the shape of its output with respect to its input. See Also @@ -448,7 +448,7 @@ def hstack(tup): Stack arrays in sequence horizontally (column wise) Take a sequence of arrays and stack them horizontally to make - a single array. hstack will rebuild arrays divided by hsplit. + a single array. Rebuild arrays divided by ``hsplit``. Parameters ---------- @@ -458,7 +458,18 @@ def hstack(tup): Returns ------- stacked : ndarray - Ndarray formed by stacking the given arrays. + The array formed by stacking the given arrays. + + See Also + -------- + vstack : Stack along first axis. + dstack : Stack along third axis. + concatenate : Join arrays. + hsplit : Split array along second axis. + + Notes + ----- + Equivalent to ``np.concatenate(tup, axis=1)`` Examples -------- @@ -512,11 +523,12 @@ def column_stack(tup): def dstack(tup): """ - Stack arrays in sequence depth wise (along third dimension) + Stack arrays in sequence depth wise (along third axis) - Take a sequence of arrays and stack them along the third axis. + Takes a sequence of arrays and stack them along the third axis + to make a single array. Rebuilds arrays divided by ``dsplit``. This is a simple way to stack 2D arrays (images) into a single - 3D array for processing. dstack will rebuild arrays divided by dsplit. + 3D array for processing. Parameters ---------- @@ -524,6 +536,22 @@ def dstack(tup): Arrays to stack. All of them must have the same shape along all but the third axis. + Returns + ------- + stacked : ndarray + The array formed by stacking the given arrays. + + See Also + -------- + vstack : Stack along first axis. + hstack : Stack along second axis. + concatenate : Join arrays. + dsplit : Split array along third axis. + + Notes + ----- + Equivalent to ``np.concatenate(tup, axis=2)`` + Examples -------- >>> a = np.array((1,2,3)) diff --git a/numpy/lib/twodim_base.py b/numpy/lib/twodim_base.py index cc33923ad..e796a065a 100644 --- a/numpy/lib/twodim_base.py +++ b/numpy/lib/twodim_base.py @@ -308,13 +308,13 @@ def tri(N, M=None, k=0, dtype=float): Number of rows in the array. M : int, optional Number of columns in the array. - By default, `M` is taken to equal to `N`. + By default, `M` is taken equal to `N`. k : int, optional The sub-diagonal below which the array is filled. - ``k = 0`` is the main diagonal, while ``k < 0`` is below it, - and ``k > 0`` is above. The default is 0. + `k` = 0 is the main diagonal, while `k` < 0 is below it, + and `k` > 0 is above. The default is 0. dtype : dtype, optional - Data type of the returned array. The default is `float`. + Data type of the returned array. The default is float. Returns ------- @@ -341,13 +341,13 @@ def tri(N, M=None, k=0, dtype=float): def tril(m, k=0): """ - Lower triangular. + Lower triangle of an array. - Return a copy of an array with elements above the k-th diagonal zeroed. + Return a copy of an array with elements above the `k`-th diagonal zeroed. Parameters ---------- - m : array-like, shape (M, N) + m : array_like, shape (M, N) Input array. k : int Diagonal above which to zero elements. @@ -377,7 +377,7 @@ def tril(m, k=0): def triu(m, k=0): """ - Upper triangular. + Upper triangle of an array. Construct a copy of a matrix with elements below the k-th diagonal zeroed. @@ -453,9 +453,9 @@ def histogram2d(x,y, bins=10, range=None, normed=False, weights=None): Parameters ---------- - x : array-like (N,) + x : array_like, shape(N,) A sequence of values to be histogrammed along the first dimension. - y : array-like (N,) + y : array_like, shape(M,) A sequence of values to be histogrammed along the second dimension. bins : int or [int, int] or array-like or [array, array], optional The bin specification: @@ -465,7 +465,7 @@ def histogram2d(x,y, bins=10, range=None, normed=False, weights=None): * the bin edges for the two dimensions (x_edges=y_edges=bins), * the bin edges in each dimension (x_edges, y_edges = bins). - range : array-like, (2,2), optional + range : array_like, shape(2,2), optional The leftmost and rightmost edges of the bins along each dimension (if not specified explicitly in the `bins` parameters): [[xmin, xmax], [ymin, ymax]]. All values outside of this range will be @@ -473,7 +473,7 @@ def histogram2d(x,y, bins=10, range=None, normed=False, weights=None): normed : boolean, optional If False, returns the number of samples in each bin. If True, returns the bin density, ie, the bin count divided by the bin area. - weights : array-like (N,), optional + weights : array-like, shape(N,), optional An array of values `w_i` weighing each sample `(x_i, y_i)`. Weights are normalized to 1 if normed is True. If normed is False, the values of the returned histogram are equal to the sum of the weights belonging to the @@ -481,13 +481,13 @@ def histogram2d(x,y, bins=10, range=None, normed=False, weights=None): Returns ------- - H : array (nx, ny) + H : ndarray, shape(nx, ny) The bidimensional histogram of samples x and y. Values in x are histogrammed along the first dimension and values in y are histogrammed along the second dimension. - xedges : array (nx,) + xedges : ndarray, shape(nx,) The bin edges along the first dimension. - yedges : array (ny,) + yedges : ndarray, shape(ny,) The bin edges along the second dimension. See Also diff --git a/numpy/lib/type_check.py b/numpy/lib/type_check.py index 0a78986ac..6f37326cc 100644 --- a/numpy/lib/type_check.py +++ b/numpy/lib/type_check.py @@ -42,7 +42,32 @@ def mintypecode(typechars,typeset='GDFgdf',default='d'): return l[0][1] def asfarray(a, dtype=_nx.float_): - """asfarray(a,dtype=None) returns a as a float array.""" + """ + Return an array converted to float type. + + Parameters + ---------- + a : array_like + Input array. + dtype : string or dtype object, optional + Float type code to coerce input array `a`. If one of the 'int' dtype, + it is replaced with float64. + + Returns + ------- + out : ndarray, float + Input `a` as a float ndarray. + + Examples + -------- + >>> np.asfarray([2, 3]) + array([ 2., 3.]) + >>> np.asfarray([2, 3], dtype='float') + array([ 2., 3.]) + >>> np.asfarray([2, 3], dtype='int8') + array([ 2., 3.]) + + """ dtype = _nx.obj2sctype(dtype) if not issubclass(dtype, _nx.inexact): dtype = _nx.float_ @@ -54,7 +79,7 @@ def real(val): Parameters ---------- - val : {array_like, scalar} + val : array_like Input array. Returns @@ -100,10 +125,27 @@ def imag(val): return asanyarray(val).imag def iscomplex(x): - """Return a boolean array where elements are True if that element - is complex (has non-zero imaginary part). + """ + Return a bool array, True if element is complex (non-zero imaginary part). For scalars, return a boolean. + + Parameters + ---------- + x : array_like + Input array. + + Returns + ------- + out : ndarray, bool + Output array. + + Examples + -------- + >>> x = np.array([1,2,3.j]) + >>> np.iscomplex(x) + array([False, False, True], dtype=bool) + """ ax = asanyarray(x) if issubclass(ax.dtype.type, _nx.complexfloating): @@ -219,7 +261,7 @@ def real_if_close(a,tol=100): Parameters ---------- - a : {array_like, scalar} + a : array_like Input array. tol : scalar Tolerance for the complex part of the elements in the array. @@ -241,6 +283,16 @@ def real_if_close(a,tol=100): 2.2204460492503131e-16. You can use 'np.finfo(np.float).eps' to print out the machine epsilon for floats. + Examples + -------- + >>> np.finfo(np.float).eps # DOCTEST +skip + 2.2204460492503131e-16 + + >>> np.real_if_close([2.1 + 4e-14j], tol = 1000) + array([ 2.1]) + >>> np.real_if_close([2.1 + 4e-13j], tol = 1000) + array([ 2.1 +4.00000000e-13j]) + """ a = asanyarray(a) if not issubclass(a.dtype.type, _nx.complexfloating): @@ -255,7 +307,24 @@ def real_if_close(a,tol=100): def asscalar(a): - """Convert an array of size 1 to its scalar equivalent. + """ + Convert an array of size 1 to its scalar equivalent. + + Parameters + ---------- + a : ndarray + Input array. + + Returns + ------- + out : scalar + Scalar of size 1 array. + + Examples + -------- + >>> np.asscalar(np.array([24])) + >>> 24 + """ return a.item() @@ -322,19 +391,28 @@ def common_type(*arrays): """ Return the inexact scalar type which is most common in a list of arrays. - The return type will always be a inexact scalar type, even if all - the arrays are integer arrays + The return type will always be an inexact scalar type, even if all the + arrays are integer arrays Parameters ---------- - arrays: sequence of array_like - Input sequence of arrays. + array1, array2, ... : ndarray + Input arrays. Returns ------- - out: data type code + out : data type code Data type code. + See Also + -------- + dtype + + Examples + -------- + >>> np.common_type(np.arange(4), np.array([45,6]), np.array([45.0, 6.0])) + <type 'numpy.float64'> + """ is_complex = False precision = 0 diff --git a/numpy/lib/ufunclike.py b/numpy/lib/ufunclike.py index 6df529609..24f35da81 100644 --- a/numpy/lib/ufunclike.py +++ b/numpy/lib/ufunclike.py @@ -7,7 +7,38 @@ __all__ = ['fix', 'isneginf', 'isposinf', 'log2'] import numpy.core.numeric as nx def fix(x, y=None): - """ Round x to nearest integer towards zero. + """ + Round to nearest integer towards zero. + + Round an array of floats element-wise to nearest integer towards zero. + The rounded values are returned as floats. + + Parameters + ---------- + x : array_like + An array of floats to be rounded + y : ndarray, optional + Output array + + Returns + ------- + out : ndarray of floats + The array of rounded numbers + + See Also + -------- + floor : Round downwards + around : Round to given number of decimals + + Examples + -------- + >>> np.fix(3.14) + 3.0 + >>> np.fix(3) + 3.0 + >>> np.fix([2.1, 2.9, -2.1, -2.9]) + array([ 2., 2., -2., -2.]) + """ x = nx.asanyarray(x) if y is None: @@ -19,7 +50,10 @@ def fix(x, y=None): def isposinf(x, y=None): """ - Return True where x is +infinity, and False otherwise. + Shows which elements of the input are positive infinity. + + Returns a numpy array resulting from an element-wise test for positive + infinity. Parameters ---------- @@ -31,16 +65,54 @@ def isposinf(x, y=None): Returns ------- y : ndarray - A boolean array where y[i] = True only if x[i] = +Inf. + A numpy boolean array with the same dimensions as the input. + If second argument is not supplied then a numpy boolean array is returned + with values True where the corresponding element of the input is positive + infinity and values False where the element of the input is not positive + infinity. + + If second argument is supplied then an numpy integer array is returned + with values 1 where the corresponding element of the input is positive + positive infinity. See Also -------- - isneginf, isfinite + isinf : Shows which elements are negative or positive infinity. + isneginf : Shows which elements are negative infinity. + isnan : Shows which elements are Not a Number (NaN). + isfinite: Shows which elements are not: Not a number, positive and + negative infinity + + Notes + ----- + Numpy uses the IEEE Standard for Binary Floating-Point for Arithmetic + (IEEE 754). This means that Not a Number is not equivalent to infinity. + Also that positive infinity is not equivalent to negative infinity. But + infinity is equivalent to positive infinity. + + Errors result if second argument is also supplied with scalar input or + if first and second arguments have different shapes. + + Numpy's definitions for positive infinity (PINF) and negative infinity + (NINF) may be change in the future versions. + Examples -------- + >>> np.isposinf(np.PINF) + array(True, dtype=bool) + >>> np.isposinf(np.inf) + array(True, dtype=bool) + >>> np.isposinf(np.NINF) + array(False, dtype=bool) >>> np.isposinf([-np.inf, 0., np.inf]) - array([ False, False, True], dtype=bool) + array([False, False, True], dtype=bool) + >>> x=np.array([-np.inf, 0., np.inf]) + >>> y=np.array([2,2,2]) + >>> np.isposinf(x,y) + array([1, 0, 0]) + >>> y + array([1, 0, 0]) """ if y is None: @@ -95,11 +167,10 @@ def log2(x, y=None): Returns ------- - y : {ndarray, scalar} + y : ndarray The logarithm to the base 2 of `x` elementwise. NaNs are returned where `x` is negative. - See Also -------- log, log1p, log10 diff --git a/numpy/lib/utils.py b/numpy/lib/utils.py index 0b2731005..d749f00b6 100644 --- a/numpy/lib/utils.py +++ b/numpy/lib/utils.py @@ -42,15 +42,23 @@ def get_include(): return d def get_numarray_include(type=None): - """Return the directory in the package that contains the numpy/*.h header - files. + """ + Return the directory that contains the numarray \\*.h header files. - Extension modules that need to compile against numpy should use this - function to locate the appropriate include directory. Using distutils: + Extension modules that need to compile against numarray should use this + function to locate the appropriate include directory. + + Notes + ----- + When using ``distutils``, for example in ``setup.py``. + :: + + import numpy as np + ... + Extension('extension_name', ... + include_dirs=[np.get_numarray_include()]) + ... - import numpy - Extension('extension_name', ... - include_dirs=[numpy.get_numarray_include()]) """ from numpy.numarray import get_numarray_include_dirs include_dirs = get_numarray_include_dirs() @@ -96,10 +104,7 @@ def deprecate(func, oldname=None, newname=None): depdoc = '%s is DEPRECATED!! -- use %s instead' % (oldname, newname,) def newfunc(*args,**kwds): - """ - Use get_include, get_numpy_include is DEPRECATED. - - """ + """Use get_include, get_numpy_include is DEPRECATED.""" warnings.warn(str1, DeprecationWarning) return func(*args, **kwds) @@ -335,18 +340,30 @@ def _makenamedict(module='numpy'): return thedict, dictlist def info(object=None,maxwidth=76,output=sys.stdout,toplevel='numpy'): - """Get help information for a function, class, or module. + """ + Get help information for a function, class, or module. + + Parameters + ---------- + object : optional + Input object to get information about. + maxwidth : int, optional + Printing width. + output : file like object open for writing, optional + Write into file like object. + toplevel : string, optional + Start search at this level. + + Examples + -------- + >>> np.info(np.polyval) # doctest: +SKIP - Example: - >>> np.info(np.polyval) # doctest: +SKIP + polyval(p, x) - polyval(p, x) + Evaluate the polymnomial p at x. - Evaluate the polymnomial p at x. + ... - Description: - If p is of length N, this function returns the value: - p[0]*(x**N-1) + p[1]*(x**N-2) + ... + p[N-2]*x + p[N-1] """ global _namedict, _dictlist # Local import to speed up numpy's import time. |