#LyX 1.5.1 created this file. For more info see http://www.lyx.org/
\lyxformat 276
\begin_document
\begin_header
\textclass mybook
\begin_preamble
\usepackage{array}
% This gives us a better font in URL links (otherwise the default
% MonoSpace font is bitmapped, and it looks horrible in PDF)
\usepackage{courier}
\usepackage{fullpage}
\usepackage{color} % so we can use red for the fixme warnings
% The hyperref package gives us a pdf with properly built
% internal navigation ('pdf bookmarks' for the table of contents,
% internal cross-reference links, web links for URLs, etc.)
% A few colors to replace the defaults for certain link types
\definecolor{darkorange}{rgb}{.71,0.21,0.01}
\definecolor{darkgreen}{rgb}{.12,.54,.11}
\usepackage[
%pdftex, % needed for pdflatex
breaklinks=true, % so long urls are correctly broken across lines
colorlinks=true,
urlcolor=blue,
linkcolor=darkorange,
citecolor=darkgreen,
]{hyperref}
% This helps prevent overly long lines that stretch beyond the margins
\sloppy
% Define a \fixme command to mark visually things needing fixing in the draft.
% For final printing or to simply disable these bright warnings, simply
% uncomment the \renewcommand redefinition below
\newcommand{\fixme}[1] {
\textcolor{red}{
{\fbox{ {\bf FIX}
\ensuremath{\blacktriangleright \blacktriangleright \blacktriangleright}}
{\bf #1}
\fbox{\ensuremath{ \blacktriangleleft \blacktriangleleft \blacktriangleleft }
} } }
}
% Uncomment the next line to make the \fixme command be a no-op
%\renewcommand{\fixme}[1]{}
%%% If you also want to use the listings package for nicely formatted
%%% Python source code, this configuration produces good on-paper and
%%% on-screen results:
\definecolor{orange}{cmyk}{0,0.4,0.8,0.2}
% Use and configure listings package for nicely formatted code
\usepackage{listings}
\lstset{
language=Python,
basicstyle=\small\ttfamily,
commentstyle=\ttfamily\color{blue},
stringstyle=\ttfamily\color{orange},
showstringspaces=false,
breaklines=true,
postbreak = \space\dots
}
\end_preamble
\language english
\inputencoding auto
\font_roman default
\font_sans default
\font_typewriter default
\font_default_family default
\font_sc false
\font_osf false
\font_sf_scale 100
\font_tt_scale 100
\graphics default
\paperfontsize 10
\spacing onehalf
\papersize custom
\use_geometry true
\use_amsmath 2
\use_esint 0
\cite_engine basic
\use_bibtopic false
\paperorientation portrait
\paperwidth 7in
\paperheight 9in
\leftmargin 1in
\topmargin 1in
\rightmargin 1in
\bottommargin 1in
\secnumdepth 3
\tocdepth 3
\paragraph_separation indent
\defskip medskip
\quotes_language english
\papercolumns 1
\papersides 1
\paperpagestyle headings
\tracking_changes false
\output_changes false
\author ""
\author ""
\end_header
\begin_body
\begin_layout Standard
\begin_inset VSpace 2in*
\end_inset
\end_layout
\begin_layout Standard
\align center
\family sans
\series bold
\size giant
Guide to NumPy
\end_layout
\begin_layout Standard
\align center
\family sans
\size larger
Travis E.
Oliphant, PhD
\newline
August 21, 2008
\end_layout
\begin_layout Standard
\begin_inset VSpace vfill
\end_inset
This book was released from a restricted distribution using a Market-Determined,
Temporary, Distribution-Restriction (MDTDR) system (see http://www.trelgol.com)
on August 21, 2008.
It is now released to the public domain and can be used as source material
for other works.
\end_layout
\begin_layout Standard
\begin_inset LatexCommand tableofcontents
\end_inset
\end_layout
\begin_layout Standard
\begin_inset FloatList table
\end_inset
\end_layout
\begin_layout Part
NumPy from Python
\end_layout
\begin_layout Chapter
Origins of NumPy
\end_layout
\begin_layout Quotation
A complex system that works is invariably found to have evolved from a simple
system that worked
\end_layout
\begin_layout Right Address
---
\emph on
John Gall
\end_layout
\begin_layout Quotation
Copy from one, it's plagiarism; copy from two, it's research.
\end_layout
\begin_layout Right Address
---
\emph on
Wilson Mizner
\end_layout
\begin_layout Standard
NumPy builds on (and is a successor to) the successful Numeric array object.
Its goal is to create the corner-stone for a useful environment for scientific
computing.
In order to better understand the people surrounding NumPy and (its library-pac
kage) SciPy, I will explain a little about how SciPy and (current) NumPy
originated.
In 1998, as a graduate student studying biomedical imaging at the Mayo
Clinic in Rochester, MN, I came across Python and its numerical extension
(Numeric) while I was looking for ways to analyze large data sets for Magnetic
Resonance Imaging and Ultrasound using a high-level language.
I quickly fell in love with Python programming which is a remarkable statement
to make about a programming language.
If I had not seen others with the same view, I might have seriously doubted
my sanity.
I became rather involved in the Numeric Python community, adding the C-API
chapter to the Numeric documentation (for which Paul Dubois graciously
made me a co-author).
\end_layout
\begin_layout Standard
As I progressed with my thesis work, programming in Python was so enjoyable
that I felt inhibited when I worked with other programming frameworks.
As a result, when a task I needed to perform was not available in the core
language, or in the Numeric extension, I looked around and found C or Fortran
code that performed the needed task, wrapped it into Python (either by
hand or using SWIG), and used the new functionality in my programs.
\end_layout
\begin_layout Standard
Along the way, I learned a great deal about the underlying structure of
Numeric and grew to admire it's simple but elegant structures that grew
out of the mechanism by which Python allows itself to be extended.
\end_layout
\begin_layout Note
Numeric was originally written in 1995 based off of an earlier Matrix Object
design by Jim Fulton which was released in 1994.
Most of the code was written by Jim Hugunin while he was a graduate student
at MIT.
He received help from many people including Jim Fulton, David Ascher, Paul
Dubois, and Konrad Hinsen.
These individuals and many others added comments, criticisms, and code
which helped the Numeric extension reach stability.
Jim Hugunin did not stay long as an active member of the community ---
moving on to write Jython and, later, Iron Python.
\end_layout
\begin_layout Standard
By operating in this need-it-make-it fashion I ended up with a substantial
library of extension modules that helped Python + Numeric become easier
to use in a scientific setting.
These early modules included raw input-output functions, a special function
library, an integration library, an ordinary differential equation solver,
some least-squares optimizers, and sparse matrix solvers.
While I was doing this laborious work, Pearu Peterson noticed that a lot
of the routines I was wrapping were written in Fortran, and there was no
simplified wrapping mechanism for Fortran subroutines (like SWIG for C).
He began the task of writing f2py which made it possible to easily wrap
Fortran programs into Python.
I helped him a little bit, mostly with testing and contributing early function-
call-back code, but he put forth the brunt of the work.
His result was simply amazing to me.
I've always been impressed with f2py, especially because I knew how much
effort writing and maintaining extension modules could be.
Anybody serious about scientific computing with Python will appreciate
that f2py is distributed along with NumPy.
\end_layout
\begin_layout Standard
When I finished my Ph.D.
in 2001, Eric Jones (who had recently completed his Ph.D.
at Duke) contacted me because he had a collection of Python modules he
had developed as part of his thesis work as well.
He wanted to combine his modules with mine into one super package.
Together with Pearu Peterson we joined our efforts, and SciPy was born
in 2001.
Since then, many people have contributed module code to SciPy including
Ed Schofield, Robert Cimrman, David M.
Cooke, Charles (Chuck) Harris, Prabhu Ramachandran, Gary Strangman, Jean-Sebast
ien Roy, and Fernando Perez.
Others such as Travis Vaught, David Morrill, Jeff Whitaker, and Louis Luangkeso
rn have contributed testing and build support.
\end_layout
\begin_layout Standard
At the start of 2005, SciPy was at release 0.3 and relatively stable for
an early version number.
Part of the reason it was difficult to stabilize SciPy was that the array
object upon which SciPy builds was undergoing a bit of an upheaval.
At about the same time as SciPy was being built, some Numeric users were
hitting up against the limited capabilities of Numeric.
In particular, the ability to deal with memory mapped files (and associated
alignment and swapping issues), record arrays, and altered error checking
modes were important but limited or non-existent in Numeric.
As a result, numarray was created by Perry Greenfield, Todd Miller, and
Rick White at the Space Science Telescope Institute as a replacement for
Numeric.
Numarray used a very different implementation scheme as a mix of Python
classes and C code (which led to slow downs in certain common uses).
While improving some capabilities, it was slow to pick up on the more advanced
features of Numeric's universal functions (ufuncs) --- never re-creating
the C-API that SciPy depended on.
This made it difficult for SciPy to
\begin_inset Quotes eld
\end_inset
convert
\begin_inset Quotes erd
\end_inset
to numarray.
\end_layout
\begin_layout Standard
Many newcomers to scientific computing with Python were told that numarray
was the future and started developing for it.
Very useful tools were developed that could not be used with Numeric (because
of numarray's change in C-API), and therefore could not be used easily
in SciPy.
This state of affairs was very discouraging for me personally as it left
the community fragmented.
Some developed for numarray, others developed as part of SciPy.
A few people even rejected adopting Python for scientific computing entirely
because of the split.
In addition, I estimate that quite a few Python users simply stayed away
from both SciPy and numarray, leaving the community smaller than it could
have been given the number of people that use Python for science and engineerin
g purposes.
\end_layout
\begin_layout Standard
It should be recognized that the split was not intentional, but simply an
outgrowth of the different and exacting demands of scientific computing
users.
My describing these events should not be construed as assigning blame to
anyone.
I very much admire and appreciate everyone I've met who is involved with
scientific computing and Python.
Using a stretched biological metaphor, it is only through the process of
dividing and merging that better results are born.
I think this concept applies to NumPy.
\end_layout
\begin_layout Standard
In early 2005, I decided to begin an effort to help bring the diverging
community together under a common framework if it were possible.
I first looked at numarray to see what could be done to add the missing
features to make SciPy work with it as a core array object.
After a couple of days of studying numarray, I was not enthusiastic about
this approach.
My familiarity with the Numeric code base no doubt biased my opinion, but
it seemed to me that the features of Numarray could be added back to Numeric
with a few fundamental changes to the core object.
This would make the transition of SciPy to a more enhanced array object
much easier in my mind.
\end_layout
\begin_layout Standard
Therefore, I began to construct this hybrid array object complete with an
enhanced set of universal (broadcasting) functions that could deal with
it.
Along the way, quite a few new features and significant enhancements were
added to the array object and its surrounding infrastructure.
This book describes the result of that year-and-a-half-long effort which
culminated with the release of NumPy 0.9.2 in early 2006 and NumPy 1.0 in
late 2006.
I first named the new package, SciPy Core, and used the scipy namespace.
However, after a few months of testing under that name, it became clear
that a separate namespace was needed for the new package.
As a result, a rapid search for a new name resulted in actually coming
back to the NumPy name which was the unofficial name of Numerical Python
but never the actual namespace.
Because the new package builds on the code-base of and is a successor to
Numeric, I think the NumPy name is fitting and hopefully not too confusing
to new users.
\end_layout
\begin_layout Standard
This book only briefly outlines some of the infrastructure that surrounds
the basic objects in NumPy to provide the additional functionality contained
in the older Numeric package (
\emph on
i.e.
\emph default
LinearAlgebra, RandomArray, FFT).
This infrastructure in NumPy includes basic linear algebra routines, Fourier
transform capabilities, and random number generators.
In addition, the f2py module is described in its own documentation, and
so is only briefly mentioned in the second part of the book.
There are also extensions to the standard Python distutils and testing
frameworks included with NumPy that are useful in constructing your own
packages built on top of NumPy.
The central purpose of this book, however, is to describe and document
the basic NumPy system that is available under the numpy namespace.
\end_layout
\begin_layout Note
The numpy namespace includes all names under the numpy.core and numpy.lib
namespaces as well.
Thus,
\family typewriter
import numpy
\family default
will also import the names from numpy.core and numpy.lib.
This is the recommended way to use numpy.
\end_layout
\begin_layout Standard
The following table gives a brief outline of the sub-packages contained
in numpy package.
\end_layout
\begin_layout Standard
\align center
\begin_inset Tabular
\begin_inset Text
\begin_layout Standard
Package
\end_layout
\end_inset
|
\begin_inset Text
\begin_layout Standard
Purpose
\end_layout
\end_inset
|
\begin_inset Text
\begin_layout Standard
Comments
\end_layout
\end_inset
|
\begin_inset Text
\begin_layout Standard
core
\end_layout
\end_inset
|
\begin_inset Text
\begin_layout Standard
basic objects
\end_layout
\end_inset
|
\begin_inset Text
\begin_layout Standard
all names exported to numpy
\end_layout
\end_inset
|
\begin_inset Text
\begin_layout Standard
lib
\end_layout
\end_inset
|
\begin_inset Text
\begin_layout Standard
additional utilities
\end_layout
\end_inset
|
\begin_inset Text
\begin_layout Standard
all names exported to numpy
\end_layout
\end_inset
|
\begin_inset Text
\begin_layout Standard
linalg
\end_layout
\end_inset
|
\begin_inset Text
\begin_layout Standard
basic linear algebra
\end_layout
\end_inset
|
\begin_inset Text
\begin_layout Standard
old LinearAlgebra from Numeric
\end_layout
\end_inset
|
\begin_inset Text
\begin_layout Standard
fft
\end_layout
\end_inset
|
\begin_inset Text
\begin_layout Standard
discrete Fourier transforms
\end_layout
\end_inset
|
\begin_inset Text
\begin_layout Standard
old FFT from Numeric
\end_layout
\end_inset
|
\begin_inset Text
\begin_layout Standard
random
\end_layout
\end_inset
|
\begin_inset Text
\begin_layout Standard
random number generators
\end_layout
\end_inset
|
\begin_inset Text
\begin_layout Standard
old RandomArray from Numeric
\end_layout
\end_inset
|
\begin_inset Text
\begin_layout Standard
distutils
\end_layout
\end_inset
|
\begin_inset Text
\begin_layout Standard
enhanced build and distribution
\end_layout
\end_inset
|
\begin_inset Text
\begin_layout Standard
improvements built on standard distutils
\end_layout
\end_inset
|
\begin_inset Text
\begin_layout Standard
testing
\end_layout
\end_inset
|
\begin_inset Text
\begin_layout Standard
unit-testing
\end_layout
\end_inset
|
\begin_inset Text
\begin_layout Standard
utility functions useful for testing
\end_layout
\end_inset
|
\begin_inset Text
\begin_layout Standard
f2py
\end_layout
\end_inset
|
\begin_inset Text
\begin_layout Standard
automatic wrapping of Fortran code
\end_layout
\end_inset
|
\begin_inset Text
\begin_layout Standard
a useful utility needed by SciPy
\end_layout
\end_inset
|
\end_inset
\end_layout
\begin_layout Chapter
Object Essentials
\end_layout
\begin_layout Quotation
Our programs last longer if we manage to build simple abstractions for ourselves...
\end_layout
\begin_layout Right Address
---
\emph on
Ron Jeffries
\end_layout
\begin_layout Quotation
I will tell you the truth as soon as I figure it out.
\end_layout
\begin_layout Right Address
---
\emph on
Wayne Birmingham
\end_layout
\begin_layout Standard
NumPy provides two fundamental objects: an N-dimensional array object (
\family typewriter
ndarray
\family default
) and a universal function object (
\family typewriter
ufunc
\family default
).
In addition, there are other objects that build on top of these which you
may find useful in your work, and these will be discussed later.
The current chapter will provide background information on just the
\family typewriter
ndarray
\family default
and the
\family typewriter
ufunc
\family default
that will be important for understanding the attributes and methods to
be discussed later.
\end_layout
\begin_layout Standard
An N-dimensional array is a homogeneous collection of
\begin_inset Quotes eld
\end_inset
items
\begin_inset Quotes erd
\end_inset
indexed using
\begin_inset Formula $N$
\end_inset
integers.
There are two essential pieces of information that define an
\begin_inset Formula $N$
\end_inset
-dimensional array: 1) the shape of the array, and 2) the kind of item the
array is composed of.
The shape of the array is a tuple of
\begin_inset Formula $N$
\end_inset
integers (one for each dimension) that provides information on how far
the index can vary along that dimension.
The other important information describing an array is the kind of item
the array is composed of.
Because every
\family typewriter
ndarray
\family default
is a homogeneous collection of exactly the same data-type, every item takes
up the same size block of memory, and each block of memory in the array
is interpreted in exactly the same way
\begin_inset Foot
status open
\begin_layout Standard
By using OBJECT arrays, one can effectively have heterogeneous arrays, but
the system still sees each element of the array as exactly the same thing
(a reference to a Python object).
\end_layout
\end_inset
.
\end_layout
\begin_layout Tip
All arrays in NumPy are indexed starting at 0 and ending at M-1 following
the Python convention.
\end_layout
\begin_layout Standard
For example, consider the following piece of code:
\end_layout
\begin_layout MyCode
>>> a = array([[1,2,3],[4,5,6]])
\newline
>>> a.shape
\newline
(2, 3)
\newline
>>> a.dtype
\newline
dtype('int32')
\end_layout
\begin_layout Note
for all code in this book it is assumed that you have first entered
\family typewriter
from numpy import *
\family default
.
In addition, any previously defined arrays are still defined for subsequent
examples.
\end_layout
\begin_layout Standard
This code defines an array of size
\begin_inset Formula $2\times3$
\end_inset
composed of 4-byte (little-endian) integer elements (on my 32-bit platform).
We can index into this two-dimensional array using two integers: the first
integer running from 0 to 1 inclusive and the second from 0 to 2 inclusive.
For example, index
\begin_inset Formula $\left(1,1\right)$
\end_inset
selects the element with value 5:
\end_layout
\begin_layout MyCode
>>> a[1,1]
\newline
5
\end_layout
\begin_layout Standard
All code shown in the shaded-boxes in this book has been (automatically)
executed on a particular version of NumPy.
The output of the code shown below shows which version of NumPy was used
to create all of the output in your copy of this book.
\end_layout
\begin_layout MyCode
>>> import numpy; print numpy.__version__
\newline
1.0.2.dev3478
\end_layout
\begin_layout Section
Data-Type Descriptors
\end_layout
\begin_layout Standard
In NumPy, an ndarray is an
\begin_inset Formula $N$
\end_inset
-dimensional array of items where each item takes up a fixed number of bytes.
Typically, this fixed number of bytes represents a number (
\emph on
e.g.
\emph default
integer or floating-point).
However, this fixed number of bytes could also represent an arbitrary record
made up of any collection of other data types.
NumPy achieves this flexibility through the use of a data-type (dtype)
object.
Every array has an associated dtype object which describes the layout of
the array data.
Every dtype
\begin_inset LatexCommand index
name "dtype"
\end_inset
object, in turn, has an associated Python type-object that determines exactly
what type of Python object is returned when an element of the array is
accessed.
The dtype objects are flexible enough to contain references to arrays of
other dtype objects and, therefore, can be used to define nested records.
This advanced functionality will be described in better detail later as
it is mainly useful for the recarray (record array) subclass that will
also be defined later.
However, all ndarrays can enjoy the flexibility provided by the dtype objects.
Figure
\begin_inset LatexCommand ref
reference "cap:Conceptual-diagram-showing"
\end_inset
provides a conceptual diagram showing the relationship between the ndarray,
its associated data-type object, and an array-scalar that is returned when
a single-element of the array is accessed.
Note that the data-type points to the type-object of the array scalar
\begin_inset LatexCommand index
name "array scalars"
\end_inset
.
An array scalar is returned using the type-object and a particular element
of the ndarray.
\end_layout
\begin_layout Standard
\begin_inset Float figure
wide false
sideways false
status open
\begin_layout Standard
\align center
\begin_inset Graphics
filename Figures/threefundamental.eps
width 90text%
keepAspectRatio
\end_inset
\end_layout
\begin_layout Standard
\begin_inset Caption
\begin_layout Standard
\begin_inset LatexCommand label
name "cap:Conceptual-diagram-showing"
\end_inset
Conceptual diagram showing the relationship between the three fundamental
objects used to describe the data in an array: 1) the ndarray itself, 2)
the data-type object that describes the layout of a single fixed-size element
of the array, 3) the array-scalar Python object that is returned when a
single element of the array is accessed.
\end_layout
\end_inset
\end_layout
\end_inset
\end_layout
\begin_layout Standard
Every dtype object is based on one of 21 built-in dtype objects.
These built-in objects allow numeric operations on a wide-variety of integer,
floating-point, and complex data types.
Associated with each data-type is a Python type object whose instances
are array scalars.
This type-object can be obtained using the
\family typewriter
type
\family default
attribute of the dtype object.
Python typically defines only one data-type of a particular data class
(one integer type, one floating-point type, etc.).
This can be convenient for some applications that don't need to be concerned
with all the ways data can be represented in a computer.
For scientific applications, however, this is not always true.
As a result, in NumPy, their are 21 different fundamental Python data-type-desc
riptor objects built-in.
These descriptors are mostly based on the types available in the C language
that CPython is written in.
However, there are a few types that are extremely flexible, such as
\family typewriter
str_
\family default
,
\family typewriter
unicode_
\family default
, and
\family typewriter
void
\family default
.
\end_layout
\begin_layout Standard
The fundamental data-types are shown in Table
\begin_inset LatexCommand ref
reference "cap:Fundamental-Data-Types"
\end_inset
.
Along with their (mostly) C-derived names, the integer, float, and complex
data-types are also available using a bit-width convention so that an array
of the right size can always be ensured (
\emph on
e.g.
\emph default
int8, float64, complex128).
The C-like names are also accessible using a character code which is also
shown in the table (use of the character codes, however, is discouraged).
Names for the data types that would clash with standard Python object names
are followed by a trailing underscore, '_'.
These data types are so named because they use the same underlying precision
as the corresponding Python data types.
Most scientific users should be able to use the array-enhanced scalar objects
in place of the Python objects.
The array-enhanced scalars inherit from the Python objects they can replace
and should act like them under all circumstances (except for how errors
are handled in math computations).
\end_layout
\begin_layout Tip
The array types
\series bold
bool
\series default
_,
\series bold
int
\series default
_,
\series bold
complex
\series default
_,
\series bold
float
\series default
_,
\series bold
object
\series default
_,
\series bold
unicode
\series default
_, and
\series bold
str_
\series default
are enhanced-scalars.
They are very similar to the standard Python types (without the trailing
underscore) and inherit from them (except for bool_ and object_).
They can be used in place of the standard Python types whenever desired.
Whenever a data type is required, as an argument, the standard Python types
are recognized as well.
\end_layout
\begin_layout Standard
Three of the data types are flexible in that they can have items that are
of an arbitrary size: the
\family typewriter
str_
\family default
type, the
\family typewriter
unicode_
\family default
type, and the
\family typewriter
void
\family default
type.
While, you can specify an arbitrary size for these types, every item in
an array is still of that specified size.
The void type, for example, allows for arbitrary records to be defined
as elements of the array, and can be used to define exotic types built
on top of the basic
\family typewriter
ndarray
\family default
.
\end_layout
\begin_layout Standard
\begin_inset Float table
wide false
sideways false
status open
\begin_layout Standard
\begin_inset Caption
\begin_layout Standard
\begin_inset LatexCommand label
name "cap:Fundamental-Data-Types"
\end_inset
Built-in array-scalar types corresponding to data-types for an ndarray.
The bold-face types correspond to standard Python types.
The object_ type is special because arrays with dtype='O' do not return
an array scalar on item access but instead return the actual object referenced
in the array.
\end_layout
\end_inset
\end_layout
\begin_layout Standard
\align center
\begin_inset Tabular
\begin_inset Text
\begin_layout Standard
Type
\end_layout
\end_inset
|
\begin_inset Text
\begin_layout Standard
Bit-Width
\end_layout
\end_inset
|
\begin_inset Text
\begin_layout Standard
Character
\end_layout
\end_inset
|
\begin_inset Text
\begin_layout Standard
\series bold
bool_
\end_layout
\end_inset
|
\begin_inset Text
\begin_layout Standard
boolXX
\end_layout
\end_inset
|
\begin_inset Text
\begin_layout Standard
\family typewriter
'?'
\end_layout
\end_inset
|
\begin_inset Text
\begin_layout Standard
byte
\end_layout
\end_inset
|
\begin_inset Text
\begin_layout Standard
intXX
\end_layout
\end_inset
|
\begin_inset Text
\begin_layout Standard
\family typewriter
'b'
\end_layout
\end_inset
|
\begin_inset Text
\begin_layout Standard
short
\end_layout
\end_inset
|
\begin_inset Text
\begin_layout Standard
\end_layout
\end_inset
|
\begin_inset Text
\begin_layout Standard
\family typewriter
'h'
\end_layout
\end_inset
|
\begin_inset Text
\begin_layout Standard
intc
\end_layout
\end_inset
|
\begin_inset Text
\begin_layout Standard
\end_layout
\end_inset
|
\begin_inset Text
\begin_layout Standard
\family typewriter
'i'
\end_layout
\end_inset
|
\begin_inset Text
\begin_layout Standard
\series bold
int_
\end_layout
\end_inset
|
\begin_inset Text
\begin_layout Standard
\end_layout
\end_inset
|
\begin_inset Text
\begin_layout Standard
\family typewriter
'l'
\end_layout
\end_inset
|
\begin_inset Text
\begin_layout Standard
longlong
\end_layout
\end_inset
|
\begin_inset Text
\begin_layout Standard
\end_layout
\end_inset
|
\begin_inset Text
\begin_layout Standard
\family typewriter
'q'
\end_layout
\end_inset
|
\begin_inset Text
\begin_layout Standard
intp
\end_layout
\end_inset
|
\begin_inset Text
\begin_layout Standard
\end_layout
\end_inset
|
\begin_inset Text
\begin_layout Standard
\family typewriter
'p'
\end_layout
\end_inset
|
\begin_inset Text
\begin_layout Standard
ubyte
\end_layout
\end_inset
|
\begin_inset Text
\begin_layout Standard
uintXX
\end_layout
\end_inset
|
\begin_inset Text
\begin_layout Standard
\family typewriter
'B'
\end_layout
\end_inset
|
\begin_inset Text
\begin_layout Standard
ushort
\end_layout
\end_inset
|
\begin_inset Text
\begin_layout Standard
\end_layout
\end_inset
|
\begin_inset Text
\begin_layout Standard
\family typewriter
'H'
\end_layout
\end_inset
|
\begin_inset Text
\begin_layout Standard
uintc
\end_layout
\end_inset
|
\begin_inset Text
\begin_layout Standard
\end_layout
\end_inset
|
\begin_inset Text
\begin_layout Standard
\family typewriter
'I'
\end_layout
\end_inset
|
\begin_inset Text
\begin_layout Standard
uint
\end_layout
\end_inset
|
\begin_inset Text
\begin_layout Standard
\end_layout
\end_inset
|
\begin_inset Text
\begin_layout Standard
\family typewriter
'L'
\end_layout
\end_inset
|
\begin_inset Text
\begin_layout Standard
ulonglong
\end_layout
\end_inset
|
\begin_inset Text
\begin_layout Standard
\end_layout
\end_inset
|
\begin_inset Text
\begin_layout Standard
\family typewriter
'Q'
\end_layout
\end_inset
|
\begin_inset Text
\begin_layout Standard
uintp
\end_layout
\end_inset
|
\begin_inset Text
\begin_layout Standard
\end_layout
\end_inset
|
\begin_inset Text
\begin_layout Standard
\family typewriter
'P'
\end_layout
\end_inset
|
\begin_inset Text
\begin_layout Standard
single
\end_layout
\end_inset
|
\begin_inset Text
\begin_layout Standard
floatXX
\end_layout
\end_inset
|
\begin_inset Text
\begin_layout Standard
\family typewriter
'f'
\end_layout
\end_inset
|
\begin_inset Text
\begin_layout Standard
\series bold
float_
\end_layout
\end_inset
|
\begin_inset Text
\begin_layout Standard
\end_layout
\end_inset
|
\begin_inset Text
\begin_layout Standard
\family typewriter
'd'
\end_layout
\end_inset
|
\begin_inset Text
\begin_layout Standard
longfloat
\end_layout
\end_inset
|
\begin_inset Text
\begin_layout Standard
\end_layout
\end_inset
|
\begin_inset Text
\begin_layout Standard
\family typewriter
'g'
\end_layout
\end_inset
|
\begin_inset Text
\begin_layout Standard
csingle
\end_layout
\end_inset
|
\begin_inset Text
\begin_layout Standard
complexXX
\end_layout
\end_inset
|
\begin_inset Text
\begin_layout Standard
\family typewriter
'F'
\end_layout
\end_inset
|
\begin_inset Text
\begin_layout Standard
\series bold
complex_
\end_layout
\end_inset
|
\begin_inset Text
\begin_layout Standard
\end_layout
\end_inset
|
\begin_inset Text
\begin_layout Standard
\family typewriter
'D'
\end_layout
\end_inset
|
\begin_inset Text
\begin_layout Standard
clongfloat
\end_layout
\end_inset
|
\begin_inset Text
\begin_layout Standard
\end_layout
\end_inset
|
\begin_inset Text
\begin_layout Standard
\family typewriter
'G'
\end_layout
\end_inset
|
\begin_inset Text
\begin_layout Standard
\series bold
object_
\end_layout
\end_inset
|
\begin_inset Text
\begin_layout Standard
\end_layout
\end_inset
|
\begin_inset Text
\begin_layout Standard
\family typewriter
'O'
\end_layout
\end_inset
|
\begin_inset Text
\begin_layout Standard
\series bold
str_
\end_layout
\end_inset
|
\begin_inset Text
\begin_layout Standard
\end_layout
\end_inset
|
\begin_inset Text
\begin_layout Standard
\family typewriter
'S#'
\end_layout
\end_inset
|
\begin_inset Text
\begin_layout Standard
\series bold
unicode_
\end_layout
\end_inset
|
\begin_inset Text
\begin_layout Standard
\end_layout
\end_inset
|
\begin_inset Text
\begin_layout Standard
\family typewriter
'U#'
\end_layout
\end_inset
|
\begin_inset Text
\begin_layout Standard
void
\end_layout
\end_inset
|
\begin_inset Text
\begin_layout Standard
\end_layout
\end_inset
|
\begin_inset Text
\begin_layout Standard
\family typewriter
'V#'
\end_layout
\end_inset
|
\end_inset
\end_layout
\end_inset
\end_layout
\begin_layout Note
The two types
\family typewriter
intp
\family default
and
\family typewriter
uintp
\family default
are not separate types.
They are names bound to a specific integer type just large enough to hold
a memory address (a pointer) on the platform.
\end_layout
\begin_layout Warning
Numeric Compatibility: If you used old typecode characters in your Numeric
code (which was never recommended), you will need to change some of them
to the new characters.
In particular, the needed changes are 'c->'S1', 'b'->'B', '1'->'b', 's'->'h',
'w'->'H', and 'u'->'I'.
These changes make the typecharacter convention more consistent with other
Python modules such as the struct module.
\end_layout
\begin_layout Standard
The fundamental data-types are arranged into a hierarchy of Python type-objects
shown in Figure
\begin_inset LatexCommand ref
reference "cap:Hierarchy-of-type"
\end_inset
.
Each of the leaves on this hierarchy correspond to actual data-types that
arrays can have (in other words, there is a built in dtype object associated
with each of these new types).
They also correspond to new Python objects that can be created.
These new objects are
\begin_inset Quotes eld
\end_inset
scalar
\begin_inset Quotes erd
\end_inset
types corresponding to each fundamental data-type.
Their purpose is to smooth out the rough edges that result when mixing
scalar and array operations.
These scalar objects will be discussed in more detail in Chapter
\begin_inset LatexCommand ref
reference "cha:Scalar-objects"
\end_inset
.
The other types in the hierarchy define particular categories of types.
These categories can be useful for testing whether or not the object returned
by
\family typewriter
self.dtype.type
\family default
is of a particular class (using
\family typewriter
issubclass
\family default
).
\end_layout
\begin_layout Standard
\begin_inset Float figure
wide false
sideways false
status open
\begin_layout Standard
\align center
\begin_inset Graphics
filename Figures/hierarchy.eps
lyxscale 75
width 95text%
keepAspectRatio
\end_inset
\end_layout
\begin_layout Standard
\begin_inset Caption
\begin_layout Standard
\begin_inset LatexCommand label
name "cap:Hierarchy-of-type"
\end_inset
Hierarchy of type objects representing the array data types.
Not shown are the two integer types
\family typewriter
intp
\family default
and
\family typewriter
uintp
\family default
which just point to the integer type that holds a pointer for the platform.
All the number types can be obtained using bit-width names as well.
\end_layout
\end_inset
\end_layout
\end_inset
\end_layout
\begin_layout Section
Basic indexing (slicing)
\end_layout
\begin_layout Standard
Indexing
\begin_inset LatexCommand index
name "indexing"
\end_inset
is a powerful tool in Python and NumPy takes full advantage of this power.
In fact, some of capabilities of Python's indexing were first established
by the needs of Numeric users.
\begin_inset Foot
status open
\begin_layout Standard
For example, the ability to index with a comma separated list of objects
and have it correspond to indexing with a tuple is a feature added to Python
at the request of the NumPy community.
The Ellipsis object was also added to Python explicitly for the NumPy community.
Extended slicing (wherein a step can be provided) was also a feature added
to Python because of Numeric.
\end_layout
\end_inset
Indexing is also sometimes called slicing in Python, and slicing for an
\family typewriter
ndarray
\family default
works very similarly as it does for other Python sequences.
There are three big differences: 1) slicing can be done over multiple dimension
s, 2) exactly one ellipsis object can be used to indicate several dimensions
at once, 3) slicing cannot be used to expand the size of an array (unlike
lists).
\end_layout
\begin_layout Standard
A few examples should make slicing more clear.
Suppose
\begin_inset Formula $A$
\end_inset
is a
\begin_inset Formula $10\times20$
\end_inset
array, then
\begin_inset Formula $A[3]$
\end_inset
is the same as
\begin_inset Formula $A[3,:]$
\end_inset
and represents the 4th length-20
\begin_inset Quotes eld
\end_inset
row
\begin_inset Quotes erd
\end_inset
of the array.
On the other hand,
\begin_inset Formula $A[:,3]$
\end_inset
represents the 4th length-10
\begin_inset Quotes eld
\end_inset
column
\begin_inset Quotes erd
\end_inset
of the array.
Every third element of the 4th column can be selected as
\begin_inset Formula $A[::3,3]$
\end_inset
.
Ellipses can be used to replace zero or more
\begin_inset Quotes eld
\end_inset
:
\begin_inset Quotes erd
\end_inset
terms.
In other words, an Ellipsis
\begin_inset LatexCommand index
name "Ellipsis"
\end_inset
object expands to zero or more full slice objects (
\begin_inset Quotes eld
\end_inset
:
\begin_inset Quotes erd
\end_inset
) so that the total number of dimensions in the slicing tuple matches the
number of dimensions in the array.
Thus, if
\begin_inset Formula $A$
\end_inset
is
\begin_inset Formula $10\times20\times30\times40$
\end_inset
, then
\begin_inset Formula $A[3:,...,4]$
\end_inset
is equivalent to
\begin_inset Formula $A[3:,:,:,4]$
\end_inset
while
\begin_inset Formula $A[...,3]$
\end_inset
is equivalent to
\begin_inset Formula $A[:,:,:,3].$
\end_inset
\end_layout
\begin_layout Standard
The following code illustrates some of these concepts:
\end_layout
\begin_layout MyCode
>>> a = arange(60).reshape(3,4,5); print a
\newline
[[[ 0 1 2 3 4]
\newline
[ 5 6 7
8 9]
\newline
[10 11 12 13 14]
\newline
[15 16 17 18 19]]
\newline
\newline
[[20 21 22 23 24]
\newline
[25 26 27
28 29]
\newline
[30 31 32 33 34]
\newline
[35 36 37 38 39]]
\newline
\newline
[[40 41 42 43 44]
\newline
[45 46 47
48 49]
\newline
[50 51 52 53 54]
\newline
[55 56 57 58 59]]]
\end_layout
\begin_layout Standard
\InsetSpace ~
\end_layout
\begin_layout MyCode
>>> print a[...,3]
\newline
[[ 3 8 13 18]
\newline
[23 28 33 38]
\newline
[43 48 53 58]]
\newline
>>> print a[1,...,3]
\newline
[23
28 33 38]
\newline
>>> print a[:,:,2]
\newline
[[ 2 7 12 17]
\newline
[22 27 32 37]
\newline
[42 47 52 57]]
\newline
>>>
print a[0,::2,::2]
\newline
[[ 0 2 4]
\newline
[10 12 14]]
\end_layout
\begin_layout Section
Memory Layout of
\family typewriter
ndarray
\end_layout
\begin_layout Standard
On a fundamental level, an
\begin_inset Formula $N$
\end_inset
-dimensional array object is just a one-dimensional sequence of memory with
fancy indexing code that maps an
\begin_inset Formula $N$
\end_inset
-dimensional index into a one-dimensional index.
The one-dimensional index is necessary on some level because that is how
memory is addressed in a computer.
The fancy indexing, however, can be very helpful for translating our ideas
into computer code.
This is because many concepts we wish to model on a computer have a natural
representation as an
\begin_inset Formula $N$
\end_inset
-dimensional array.
While this is especially true in science and engineering, it is also applicable
to many other arenas which can be appreciated by considering the popularity
of the spreadsheet as well as
\begin_inset Quotes eld
\end_inset
image processing
\begin_inset Quotes erd
\end_inset
applications.
\end_layout
\begin_layout Warning
Some high-level languages give pre-eminence to a particular use of 2-dimensional
arrays as Matrices.
In NumPy, however, the core object is the more general
\begin_inset Formula $N$
\end_inset
-dimensional array.
NumPy defines a matrix object as a sub-class of the N-dimensional array.
\end_layout
\begin_layout Standard
In order to more fully understand the array object along with its attributes
and methods it is important to learn more about how an
\begin_inset Formula $N$
\end_inset
-dimensional array is represented in the computer's memory.
A complete understanding of this layout is only essential for optimizing
algorithms operating on general purpose arrays.
But, even for the casual user, a general understanding of memory layout
will help to explain the use of certain array attributes that may otherwise
be mysterious.
\end_layout
\begin_layout Subsection
Contiguous Memory Layout
\end_layout
\begin_layout Standard
There is a fundamental ambiguity in how the mapping to a one-dimensional
index can take place which is illustrated for a 2-dimensional array in
Figure
\begin_inset LatexCommand ref
reference "cap:Options-for-memory"
\end_inset
.
In that figure, each block represents a chunk of memory that is needed
for representing the underlying array element.
For example, each block could represent the 8 bytes needed to represent
a double-precision floating point number.
\end_layout
\begin_layout Standard
In the figure, two arrays are shown, a
\begin_inset Formula $4x3$
\end_inset
array and a
\begin_inset Formula $3x4$
\end_inset
array.
Each of these arrays takes 12 blocks of memory shown as a single, contiguous
segment.
How this memory is used to form the abstract 2-dimensional array can vary,
however, and the
\family typewriter
ndarray
\family default
object supports both styles.
Which style is in use can be interrogated by the use of the flags attribute
which returns a dictionary of the state of array flags.
\end_layout
\begin_layout Standard
\begin_inset Float figure
wide false
sideways false
status open
\begin_layout Standard
\align center
\begin_inset Graphics
filename Figures/contiguous.eps
width 85text%
keepAspectRatio
\end_inset
\end_layout
\begin_layout Standard
\begin_inset Caption
\begin_layout Standard
\begin_inset LatexCommand label
name "cap:Options-for-memory"
\end_inset
Options for memory layout of a 2-dimensional array.
\end_layout
\end_inset
\end_layout
\end_inset
\end_layout
\begin_layout Standard
In the C-style of
\begin_inset Formula $N$
\end_inset
-dimensional indexing shown on the left of Figure
\begin_inset LatexCommand ref
reference "cap:Options-for-memory"
\end_inset
the last
\begin_inset Formula $N$
\end_inset
-dimensional index
\begin_inset Quotes eld
\end_inset
varies the fastest.
\begin_inset Quotes erd
\end_inset
In other words, to move through computer memory sequentially, the last
index is incremented first, followed by the second-to-last index and so
forth.
Some of the algorithms in NumPy that deal with
\begin_inset Formula $N$
\end_inset
-dimensional arrays work best with this kind of data.
\end_layout
\begin_layout Standard
In the Fortran-style of
\begin_inset Formula $N$
\end_inset
-dimensional indexing shown on the right of Figure
\begin_inset LatexCommand ref
reference "cap:Options-for-memory"
\end_inset
, the first
\begin_inset Formula $N$
\end_inset
-dimensional index
\begin_inset Quotes eld
\end_inset
varies the fastest.
\begin_inset Quotes erd
\end_inset
Thus, to move through computer memory sequentially, the first index is
incremented first until it reaches the limit in that dimension, then the
second index is incremented and the first index is reset to zero.
While NumPy can be compiled without the use of a Fortran compiler, several
modules of SciPy (available separately) rely on underlying algorithms written
in Fortran.
Algorithms that work on
\begin_inset Formula $N$
\end_inset
-dimensional arrays that are written in Fortran typically expect Fortran-style
arrays.
\end_layout
\begin_layout Standard
The two-styles of memory layout for arrays are connected through the transpose
operation.
Thus, if
\begin_inset Formula $A$
\end_inset
is a (contiguous) C-style array, then the same block of memory can be used
to represent
\begin_inset Formula $A^{T}$
\end_inset
as a (contiguous) Fortran-style array.
This kind of understanding can be useful when trying to optimize the wrapping
of Fortran subroutines, or if a more detailed understanding of how to write
algorithms for generally-indexed arrays is desired.
But, fortunately, the casual user who does not care if an array is copied
occasionally to get it into the right orientation needed for a particular
algorithm can forget about how the array is stored in memory and just visualize
it as an
\begin_inset Formula $N$
\end_inset
-dimensional array (that is, after all, the whole point of creating the
\family typewriter
ndarray
\family default
object in the first place).
\end_layout
\begin_layout Subsection
Non-contiguous memory layout
\end_layout
\begin_layout Standard
Both of the examples presented above are
\emph on
single-segment
\begin_inset LatexCommand index
name "single-segment"
\end_inset
\emph default
arrays where the entire array is visited by sequentially marching through
memory one element at a time.
When an algorithm in C or Fortran expects an N-dimensional array, this
single segment (of a certain fundamental type) is usually what is expected
along with the shape
\begin_inset Formula $N$
\end_inset
-tuple.
With a single-segment of memory representing the array, the one-dimensional
index into computer memory can always be computed from the
\begin_inset Formula $N$
\end_inset
-dimensional index.
This concept is explored further in the following paragraphs.
\end_layout
\begin_layout Standard
Let
\begin_inset Formula $n_{i}$
\end_inset
be the value of the
\begin_inset Formula $i^{\textrm{th}}$
\end_inset
index into an array whose shape is represented by the
\begin_inset Formula $N$
\end_inset
integers
\begin_inset Formula $d_{i}$
\end_inset
(
\begin_inset Formula $i=0\ldots N-1).$
\end_inset
Then, the one-dimensional index into a C-style contiguous array is
\begin_inset Formula \[
n^{C}=\sum_{i=0}^{N-1}n_{i}\prod_{j=i+1}^{N-1}d_{j}\]
\end_inset
while the one-dimensional index into a Fortran-style contiguous array is
\begin_inset Formula \[
n^{F}=\sum_{i=0}^{N-1}n_{i}\prod_{j=0}^{i-1}d_{j}.\]
\end_inset
In these formulas we are assuming that
\begin_inset Formula \[
\prod_{j=k}^{m}d_{j}=d_{k}d_{k+1}\cdots d_{m-1}d_{m}\]
\end_inset
so that if
\begin_inset Formula $m>> a = arange(6, 10); print a
\newline
[6 7 8 9]
\newline
>>> b = arange(12, 17); print b
\newline
[12
13 14 15 16]
\newline
>>> table = a[:,newaxis] * b
\newline
>>> print table
\newline
[[ 72 78 84 90
96]
\newline
[ 84 91 98 105 112]
\newline
[ 96 104 112 120 128]
\newline
[108 117 126 135 144]]
\end_layout
\begin_layout Section
Summary of new features
\end_layout
\begin_layout Standard
More information about using arrays in Python can be found in the old Numeric
documentation at
\begin_inset LatexCommand htmlurl
name "http://numeric.scipy.org"
target "http://numeric.scipy.org"
\end_inset
.
Quite a bit of that documentation is still accurate, especially in the
discussion of array basics.
There are significant differences, however, and this book seeks to explain
them in detail.
The following list tries to summarize the significant new features (over
Numeric) available in the
\family typewriter
ndarray
\family default
and
\family typewriter
ufunc
\family default
objects of NumPy:
\end_layout
\begin_layout Enumerate
more data types (all standard C-data types plus complex floats, Boolean,
string, unicode, and void *);
\end_layout
\begin_layout Enumerate
flexible data types where each array can have a different itemsize (but
all elements of the same array still have the same itemsize);
\end_layout
\begin_layout Enumerate
there is a true Python scalar type (contained in a hierarchy of types) for
every data-type an array can have;
\end_layout
\begin_layout Enumerate
data-type objects define the data-type with support for data-type objects
with fields and subarrays which allow record arrays with nested records;
\end_layout
\begin_layout Enumerate
many more array methods in addition to functional counterparts;
\end_layout
\begin_layout Enumerate
attributes more clearly distinguished from methods (attributes are intrinsic
parts of an array so that setting them changes the array itself);
\end_layout
\begin_layout Enumerate
array scalars covering all data types which inherit from Python scalars
when appropriate;
\end_layout
\begin_layout Enumerate
arrays can be misaligned, swapped, and in Fortran order in memory (facilitates
memory-mapped arrays);
\end_layout
\begin_layout Enumerate
arrays can be more easily read from text files and created from buffers
and iterators;
\end_layout
\begin_layout Enumerate
arrays can be quickly written to files in text and/or binary mode;
\end_layout
\begin_layout Enumerate
arrays support the removal of the 64-bit memory limitation as long as you
have Python 2.5 or later;
\end_layout
\begin_layout Enumerate
fancy indexing can be done on arrays using integer sequences and Boolean
masks;
\end_layout
\begin_layout Enumerate
coercion rules are altered for mixed scalar / array operations so that scalars
(anything that produces a 0-dimensional array internally) will not determine
the output type in such cases.
\end_layout
\begin_layout Enumerate
when coercion is needed, temporary buffer-memory allocation is limited to
a user-adjustable size;
\end_layout
\begin_layout Enumerate
errors are handled through the IEEE floating point status flags and there
is flexibility on a per-thread level for handling these errors;
\end_layout
\begin_layout Enumerate
one can register an error callback function in Python to handle errors are
set to 'call' for their error handling;
\end_layout
\begin_layout Enumerate
ufunc reduce, accumulate, and reduceat can take place using a different
type then the array type if desired (without copying the entire array);
\end_layout
\begin_layout Enumerate
ufunc output arrays passed in can be a different type than expected from
the calculation;
\end_layout
\begin_layout Enumerate
ufuncs take keyword arguments which can specify 1) the error handling explicitly
and 2) the specific 1-d loop to use by-passing the type-coercion detection.
\end_layout
\begin_layout Enumerate
arbitrary classes can be passed through ufuncs (__array_wrap__ and __array_prior
ity__ expand previous __array__ method);
\end_layout
\begin_layout Enumerate
ufuncs can be easily created from Python functions;
\end_layout
\begin_layout Enumerate
ufuncs have attributes to detail their behavior, including a dynamic doc
string that automatically generates the calling signature;
\end_layout
\begin_layout Enumerate
several new ufuncs (frexp, modf, ldexp, isnan, isfinite, isinf, signbit);
\end_layout
\begin_layout Enumerate
new types can be registered with the system so that specialized ufunc loops
can be written over new type objects;
\end_layout
\begin_layout Enumerate
new types can also register casting functions and rules for fitting into
the
\begin_inset Quotes eld
\end_inset
can-cast
\begin_inset Quotes erd
\end_inset
hierarchy;
\end_layout
\begin_layout Enumerate
C-API enhanced so that more of the functionality is available from compiled
code;
\end_layout
\begin_layout Enumerate
C-API enhanced so array structure access can take place through macros;
\end_layout
\begin_layout Enumerate
new iterator objects created for easy handling in C of non-contiguous arrays;
\end_layout
\begin_layout Enumerate
new multi-iterator object created for easy handling in C of broadcasting;
\end_layout
\begin_layout Enumerate
types have more functions associated with them (no magic function lists
in the C-code).
Any function needed is part of the type structure.
\end_layout
\begin_layout Standard
All of these enhancements will be documented more thoroughly in the remaining
portions of this book.
\end_layout
\begin_layout Section
Summary of differences with Numeric
\end_layout
\begin_layout Standard
An effort was made to retain backwards compatibility with Numeric all the
way to the C-level.
This was mostly accomplished, with a few changes that needed to be made
for consistency of the new system.
If you are just starting out with NumPy, then this section may be skipped.
\end_layout
\begin_layout Standard
There are two steps (one required and one optional) to converting code that
works with Numeric to work fully with NumPy The first step uses a compatibility
layer and requires only small changes which can be handled by the numpy.oldnumer
ic.alter_code1 module.
Code written to the compatibility layer will work and be supported.
The purpose of the compatibility layer is to make it easy to convert to
NumPy and many codes may only take this first step and work fine with NumPy.
The second step is optional as it removes dependency on the compatibility
layer and therefore requires a few more extensive changes.
Many of these changes can be performed by the numpy.oldnumeric.alter_code2
module, but you may still need to do some final tweaking by hand.
Because many users will probably be content to only use the first step,
the alter_code2 module for second-stage migration may not be as complete
as it otherwise could be.
\end_layout
\begin_layout Subsection
First-step changes
\end_layout
\begin_layout Standard
In order to use the compatibility layer there are still a few changes that
need to be made to your code.
Many of these changes can be made by running the alter_code1 module with
your code as input.
\end_layout
\begin_layout Enumerate
Importing (the alter_code1 module handles all these changes)
\end_layout
\begin_deeper
\begin_layout Enumerate
import Numeric --> import numpy.oldnumeric as Numeric
\end_layout
\begin_layout Enumerate
import Numeric as XX --> import numpy.oldnumeric as XX
\end_layout
\begin_layout Enumerate
from Numeric import ,... --> from numpy.oldnumeric import ,...,
\end_layout
\begin_layout Enumerate
from Numeric import * --> from numpy.oldnumeric import *
\end_layout
\begin_layout Enumerate
Similar name changes need to be made for Matrix, MLab, UserArray, LinearAlgebra,
RandomArray RNG, RNG.Statistics, and FFT.
The new names are numpy.oldnumeric. where is matrix, mlab, user_array,
linear_algebra, random_array, rng, rng_stats, and fft.
\end_layout
\begin_layout Enumerate
multiarray and umath (if you used them directly) are now numpy.core.multiarray
and numpy.core.umath, but it is more future proof to replace usages of these
internal modules with numpy.oldnumeric.
\end_layout
\end_deeper
\begin_layout Enumerate
Method name changes and methods converted to attributes.
The alter_code1 module handles all these changes.
\end_layout
\begin_deeper
\begin_layout Enumerate
\emph on
arr
\emph default
.typecode() -->
\emph on
arr
\emph default
.dtype.char
\end_layout
\begin_layout Enumerate
\emph on
arr
\emph default
.iscontiguous() -->
\emph on
arr
\emph default
.flags.contiguous
\end_layout
\begin_layout Enumerate
\emph on
arr
\emph default
.byteswapped() -->
\emph on
arr
\emph default
.byteswap()
\end_layout
\begin_layout Enumerate
\emph on
arr
\emph default
.toscalar() -->
\emph on
arr
\emph default
.item()
\end_layout
\begin_layout Enumerate
\emph on
arr
\emph default
.itemsize() -->
\emph on
arr
\emph default
.itemsize
\end_layout
\begin_layout Enumerate
\emph on
arr
\emph default
.spacesaver() eliminated
\end_layout
\begin_layout Enumerate
\emph on
arr
\emph default
.savespace() eliminated
\end_layout
\end_deeper
\begin_layout Enumerate
Some of the typecode characters have changed to be more consistent with
other Python modules (array and struct).
You should only notice this change if you used the actual typecode characters
(instead of the named constants).
\newline
The alter_code1 module will change uses of 'b' to 'B' for internal Numeric
functions that it knows about because NumPy will interpret 'b' to mean
a signed byte type (instead of the old unsigned).
It will also change the character codes when they are used explicitly in
the .astype method.
In the compatibility layer (and only in the compatibility layer), typecode-requ
iring function calls (
\emph on
e.g.
\emph default
zeros, array) understand the old typecode characters.
\newline
The changes are (Numeric --> NumPy):
\end_layout
\begin_deeper
\begin_layout Enumerate
'b' --> 'B'
\end_layout
\begin_layout Enumerate
'1' --> 'b'
\end_layout
\begin_layout Enumerate
's' --> 'h'
\end_layout
\begin_layout Enumerate
'w' --> 'H'
\end_layout
\begin_layout Enumerate
'u' --> 'I'
\end_layout
\end_deeper
\begin_layout Enumerate
\emph on
arr.
\emph default
flat now returns an indexable 1-D iterator.
This behaves correctly when passed to a function, but if you expected methods
or attributes on
\emph on
arr.
\emph default
flat --- besides .copy() --- then you will need to replace
\emph on
arr
\emph default
.flat with
\emph on
arr.
\emph default
ravel() (copies only when necessary) or
\emph on
arr.
\emph default
flatten() (always copies).
The alter_code1 module will change
\emph on
arr
\emph default
.flat to
\emph on
arr
\emph default
.ravel() unless you used the construct
\emph on
arr
\emph default
.flat = obj or
\emph on
arr
\emph default
.flat[ind].
\end_layout
\begin_layout Enumerate
If you used type-equality testing on the objects returned from arrays, then
you need to change this to isinstance testing.
Thus type(a[0]) is float or type(a[0]) == float should be changed to isinstance
(a[0], float).
This is because array scalar objects are now returned from arrays.
These inherit from the Python scalars where they can, but define their
own methods and attributes.
This conversion is done by alter_code1 for the types (float, int, complex,
and ArrayType)
\end_layout
\begin_layout Enumerate
If your code should produce 0-d arrays.
These no-longer have a length as they should be interpreted similarly to
real scalars which don't have a length.
\end_layout
\begin_layout Enumerate
Arrays cannot be tested for truth value unless they are empty (returns False)
or have only one element.
This means that if Z: where Z is an array will fail (unless Z is empty
or has only one element).
Also the 'and' and 'or' operations (which test for object truth value)
will also fail on arrays of more than one element.
Use the .any() and .all() methods to test for truth value of an array.
\end_layout
\begin_layout Enumerate
Masked arrays return a special nomask object instead of None when there
is no mask on the array for the functions getmask and attribute access
\emph on
arr
\emph default
.mask
\end_layout
\begin_layout Enumerate
Masked array functions have a default axis of None (meaning ravel), make
sure to specify an axis if your masked arrays are larger than 1-d.
\end_layout
\begin_layout Enumerate
If you used the construct
\family typewriter
arr.shape=
\family default
, this will not work for array scalars (which can be returned from array
operations).
You cannot set the shape of an array-scalar (you can read it though).
As a result, for more general code you should use
\family typewriter
arr=arr.reshape()
\family default
which works for both array-scalars and arrays.
\end_layout
\begin_layout Standard
The alter_code1 script should handle the changes outlined in steps 1-5 above.
The final incompatibilities in 6-9 are less common and must be modified
by hand if necessary.
\end_layout
\begin_layout Subsection
Second-step changes
\end_layout
\begin_layout Standard
During the second phase of migration (should it be necessary) the compatibility
layer is dropped.
This phase requires additional changes to your code.
There is another conversion module (alter_code2) which can help but it
is not complete.
The changes required to drop dependency on the compatibility layer are
\end_layout
\begin_layout Enumerate
Importing
\end_layout
\begin_deeper
\begin_layout Enumerate
numpy.oldnumeric --> numpy
\end_layout
\begin_layout Enumerate
from numpy.oldnumeric import * --> from numpy import * (this may clobber
more names and therefore require further fixes to your code but then you
didn't do this regularly anyway did you).
The recommended procedure if this replacement causes problems is to fix
the use of from numpy.oldnumeric import * to extract only the required names
and then continue.
\end_layout
\begin_layout Enumerate
numpy.oldnumeric.mlab --> None, the functions come from other places.
\end_layout
\begin_layout Enumerate
numpy.oldnumeric.linear_algebra --> numpy.lilnalg with name changes to the
functions (made lower case and shorter).
\end_layout
\begin_layout Enumerate
numpy.oldnumeric.random_array --> numpy.random with some name changes to the
functions.
\end_layout
\begin_layout Enumerate
numpy.oldnumeic.fft --> numpy.fft with some name changes to the functions.
\end_layout
\begin_layout Enumerate
numpy.oldnumeric.rng --> None
\end_layout
\begin_layout Enumerate
numpy.oldnumeric.rng_stats --> None
\end_layout
\begin_layout Enumerate
numpy.oldnumeric.user_array --> numpy.lib.user_array
\end_layout
\begin_layout Enumerate
numpy.oldnumeric.matrix --> numpy
\end_layout
\end_deeper
\begin_layout Enumerate
The typecode names are all lower-case and refer to type-objects corresponding
to array scalars.
The character codes are understood by array-creation functions but are
not given names.
All named type constants should be replaced with their lower-case equivalents.
Also, the old character codes '1', 's', 'w', and 'u' are not understood
as data-types.
It is probably easiest to manually replace these with Int8, Int16, UInt16,
and UInt32 and let the alter_code2 script convert the names to lower-case
typeobjects.
\end_layout
\begin_layout Enumerate
Keyword and argument changes
\end_layout
\begin_deeper
\begin_layout Enumerate
All
\family typewriter
typecode=
\family default
keywords must be changed to
\family typewriter
dtype=
\family default
.
\end_layout
\begin_layout Enumerate
The
\family typewriter
savespace
\family default
keyword argument has been removed from all functions where it was present
(array, sarray, asarray, ones, and zeros).
The sarray function is equivalent to asarray.
\end_layout
\end_deeper
\begin_layout Enumerate
The default data-type in NumPy is float unlike in Numeric (and numpy.oldnumeric)
where it was int.
There are several functions affected by this so that if your code was relying
on the default data-type, then it must be changed to explicitly add dtype=int.
\end_layout
\begin_layout Enumerate
The nonzero function in NumPy returns a tuple of index arrays just like
the corresponding method.
There is a flatnonzero function that first ravels the array and then returns
a single index array.
This function should be interchangeable with the old use of nonzero.
\end_layout
\begin_layout Enumerate
The default axis is None (instead of 0) to match the methods for the functions
take, repeat, sum, average, product, sometrue, alltrue, cumsum, and cumproduct
(from Numeric) and also for the functions average, max, min, ptp, prod,
std, and mean (from MLab).
\end_layout
\begin_layout Enumerate
The default axis is None (instead of -1) to match the methods for the functions
argmin, argmax, compress
\end_layout
\begin_layout Subsection
Updating code that uses Numeric using alter_codeN
\end_layout
\begin_layout Standard
Despite the long list of changes that might be needed given above, it is
likely that your code does not use any of the incompatible corners and
it should not be too difficult to convert from Numeric to NumPy.
For example all of SciPy was converted in about 2-3 days.
The needed changes are largely search-and replace type changes, and the
alter_codeN modules can help.
The modules have two functions which help the process:
\end_layout
\begin_layout Description
convertfile (filename, orig=1)
\end_layout
\begin_layout Description
\InsetSpace ~
Convert the file with the given filename to use NumPy.
If orig is True, then a backup is first made and given the name filename.orig.
Then, the file is converted and the updated code written over the top of
the old file.
\end_layout
\begin_layout Description
convertall (direc=os.path.curdir, orig=1)
\end_layout
\begin_layout Description
\InsetSpace ~
Converts all the
\begin_inset Quotes eld
\end_inset
.py
\begin_inset Quotes erd
\end_inset
files in the given directory to use NumPy.
Backups of all the files are first made if orig is True as explained for
the convertfile function.
\end_layout
\begin_layout Description
convertsrc (direc=os.path.curdir, ext=None, orig=1)
\end_layout
\begin_layout Description
\InsetSpace ~
Replace
\family typewriter
''Numeric/arrayobject.h
\begin_inset Quotes erd
\end_inset
\family default
with
\family typewriter
''numpy/oldnumeric.h
\begin_inset Quotes erd
\end_inset
\family default
in all files ending in the list of extensions given by ext (if ext is None,
then all files are updated).
If orig is True, then first make a backup file with
\begin_inset Quotes eld
\end_inset
.orig
\begin_inset Quotes erd
\end_inset
as the extension.
\end_layout
\begin_layout Description
converttree (direc=os.path.curdir)
\end_layout
\begin_layout Description
\InsetSpace ~
Walks the tree pointed to by direc and converts all
\begin_inset Quotes eld
\end_inset
.py
\begin_inset Quotes erd
\end_inset
modules in each sub-directory to use NumPy.
No backups of the files are made.
Also, converts all .h and .c files to replace
\family typewriter
''Numeric/arrayobject.h
\begin_inset Quotes erd
\end_inset
\family default
with
\family typewriter
''numpy/oldnumeric.h
\begin_inset Quotes erd
\end_inset
\family default
so that NumPy is used.
\end_layout
\begin_layout Subsection
Changes to think about
\end_layout
\begin_layout Standard
Even if you don't make changes to your old code.
If you are used to coding in Numeric, then you may need to adjust your
coding style a bit.
This list provides some helpful things to remember.
\end_layout
\begin_layout Enumerate
Switch from using typecode characters to bitwidth type names or c-type names
\end_layout
\begin_layout Enumerate
Convert use of uppercase type-names Int32, Float, etc., to lower case int32,
float, etc.
\end_layout
\begin_layout Enumerate
Convert use of functions to method calls where appropriate but explicitly
specify any axis arguments for arrays greater than 1-d.
\end_layout
\begin_layout Enumerate
The names for standard computations like Fourier transforms, linear algebra,
and random-number generation have changed to conform to the standard of
lower-case names possibly separated by an underscore.
\end_layout
\begin_layout Enumerate
Look for ways to take advantage of advanced slicing, but remember it always
returns a copy and may be slower at times.
\end_layout
\begin_layout Enumerate
Remove any kludges you inserted to eliminate problems with Numeric that
are now gone.
\end_layout
\begin_layout Enumerate
Look for ways to take advantage of new features like expanded data-types
(record-arrays).
\end_layout
\begin_layout Enumerate
See if you can inherit from the ndarray directly, rather than using user_array.co
ntainer (UserArray).
However, if you were using UserArray in a multiple-inheritance hierarchy
this is going to be more difficult and you can continue to use the standard
container class in user_array (but notice the name change).
\end_layout
\begin_layout Enumerate
Watch your usage of scalars extracted from arrays.
Treating Numeric arrays like lists and then doing math on the elements
1 by 1 was always about 2x slower than using real lists in Python.
This can now be 3x-6x slower than using lists in NumPy because of the increased
complexity of both the indexing of ndarrays and the math of array scalars.
If you must select individual scalars from NumPy, you can get some speed
increases by using the item method to get a standard Python scalar from
an N-d array and by using the itemset method to place a scalar into a particula
r location in the N-d array.
This complicates the appearance of the code, however.
Also, when using these methods inside a loop, be sure to assign the methods
to a local variable to avoid the attribute look-up at each loop iteration.
\end_layout
\begin_layout Standard
Throughout this book, warnings are inserted when compatibility issues with
old Numeric are raised.
While you may not need to make any changes to get code to run with the
ndarray object, you will likely want to make changes to take advantage
of the new features of NumPy.
If you get into a jam during the conversion process, you should be aware
that Numeric and NumPy can both be used together and they will not interfere
with each other.
In addition, if you have Numeric 24.0 or newer, they can even share the
same memory.
This makes it easy to use NumPy as well as third-party tools that have
not made the switch from Numeric yet.
\end_layout
\begin_layout Section
Summary of differences with Numarray
\end_layout
\begin_layout Standard
Conversion from Numarray can also be relatively painless, depending on how
dependent your code is on the specific structure of the Numarray ufuncs,
cfuncs, and various array-like objects.
The internals of Numarray can be quite different and so depending on how
intimately you used those internals adapting to NumPy can be more or less
difficult.
C-code that used the Numarray C-API can be easily adapted because NumPy
includes a Numarray-compatible C-API module.
All you need to do is replace usage of
\begin_inset Quotes eld
\end_inset
numarray/libnumarray.h
\begin_inset Quotes erd
\end_inset
with
\begin_inset Quotes eld
\end_inset
numpy/libnumarray.h
\begin_inset Quotes erd
\end_inset
and be sure the directory returned from the Python command numpy.get_numarray_in
clude() is included in the list of directories used for compilation.
\end_layout
\begin_layout Standard
On the Python-side the largest number of differences are in the methods
and attributes of the array and the way array data-types are represented.
In addition, arrays containing Python Objects, strings, and records are
an integral part of the array object and not handled using a separate class
(although enhanced separate classes do exist for the case of character
arrays and record arrays).
\end_layout
\begin_layout Standard
As is the case with Numeric, there is a two-step process available for migrating
code written for Numarray to work with NumPy.
This process involves running functions in the modules alter_code1 and
alter_code2 located in the numarray sub-package of NumPy.
These modules have interfaces identical to the ones that convert Numeric
code, but they work to convert code written for numarray.
The first module will convert your code to use the numarray compatibility
module (numpy.numarray), while the second will try and help convert code
to move away from dependency on the compatibility module.
Because many users will probably be content to only use the first step,
the alter_code2 module for second-stage migration may not be as complete
as it otherwise could be.
\end_layout
\begin_layout Standard
Also, the alter_code1 module is not guaranteed to convert every piece of
working numarray code to use NumPy.
If your code relied on the internal module structure of numarray or on
how the class hierarchy was laid out, then it will need to be changed manually
to run with NumPy.
Of course you can still use your code with Numarray installed side-by-side
and the two array objects should be able to exchange data without copying.
\end_layout
\begin_layout Subsection
First-step changes
\end_layout
\begin_layout Standard
The alter_code1 script makes the following import and attribute/method changes
\end_layout
\begin_layout Subsubsection
Import changes
\end_layout
\begin_layout Itemize
import numarray --> import numpy.numarray as numarray
\end_layout
\begin_layout Itemize
import numarray.package --> import numpy.numarray.package as numarray_package
with all usages of numarray.package in the code replaced by numarray_package
\end_layout
\begin_layout Itemize
import numarray as --> import numpy.numarray s
\end_layout
\begin_layout Itemize
import numarray.package as --> import numpy.numarray.package as
\end_layout
\begin_layout Itemize
from numarray import --> from numpy.numarray import
\end_layout
\begin_layout Itemize
from numarray.package import --> from numpy.numarray.package import
\end_layout
\begin_layout Subsubsection
Attribute and method changes
\end_layout
\begin_layout Itemize
.imaginary --> .imag
\end_layout
\begin_layout Itemize
.flat --> probably .ravel() (Many usages will still work correctly because
you can index and assign to self.flat)
\end_layout
\begin_layout Itemize
.byteswapped() --> .byteswap(False)
\end_layout
\begin_layout Itemize
.byteswap() --> .byteswap(True) (Returns a reference to self instead of None).
\end_layout
\begin_layout Itemize
self.info() --> numarray.info(self)
\end_layout
\begin_layout Itemize
.isaligned() --> .flags.aligned
\end_layout
\begin_layout Itemize
.isbyteswapped() --> not .dtype.isnative (the byte-order is a property of the
data-type object not the array itself in NumPy).
\end_layout
\begin_layout Itemize
.iscontiguous() --> .flags.c_contiguous
\end_layout
\begin_layout Itemize
.is_c_array() --> .dtype.isnative and .flags.carray
\end_layout
\begin_layout Itemize
.is_fortran_contiguous() --> .flags.f_contiguous
\end_layout
\begin_layout Itemize
.is_f_array() --> .dtype.isnative and .flags.farray
\end_layout
\begin_layout Itemize
.itemsize() --> .itemsize
\end_layout
\begin_layout Itemize
.nelements() --> .size
\end_layout
\begin_layout Itemize
self.new(type) --> numarray.newobj(self, type)
\end_layout
\begin_layout Itemize
.repeat(r) --> .repeat(r, axis=0)
\end_layout
\begin_layout Itemize
.size() --> .size
\end_layout
\begin_layout Itemize
.type() --> numarray.typefrom(self)
\end_layout
\begin_layout Itemize
.typecode() --> .dtype.char
\end_layout
\begin_layout Itemize
.stddev() --> .std()
\end_layout
\begin_layout Itemize
.togglebyteorder() --> numarray.togglebyteorder(self)
\end_layout
\begin_layout Itemize
.getshape() --> .shape
\end_layout
\begin_layout Itemize
.setshape(obj) --> .shape = obj
\end_layout
\begin_layout Itemize
.getflat() --> .ravel()
\end_layout
\begin_layout Itemize
.getreal() --> .real
\end_layout
\begin_layout Itemize
.setreal(obj) --> .real = obj
\end_layout
\begin_layout Itemize
.getimag() --> .imag
\end_layout
\begin_layout Itemize
.setimag(obj) --> .imag = obj
\end_layout
\begin_layout Itemize
.getimaginary() --> .imag
\end_layout
\begin_layout Itemize
.setimaginary(obj) --> .imag = obj
\end_layout
\begin_layout Subsection
Second-step changes
\end_layout
\begin_layout Standard
One of the notable differences is that several functions (array, arange,
fromfile, and fromstring) do not take the shape= keyword argument.
Instead you simply reshape the result using the reshape method.
Another notable difference is that instead of allowing typecode=, type=,
and dtype= variants for specifying the data-types, you must use the dtype=
keyword.
Other differences include
\end_layout
\begin_layout Itemize
matrixmultiply(a,b) --> dot(a,b)
\end_layout
\begin_layout Itemize
innerproduct(a,b) --> inner(a,b)
\end_layout
\begin_layout Itemize
outerproduct(a,b) --> outer(a,b)
\end_layout
\begin_layout Itemize
kroneckerproduct(a,b) --> kron(a,b)
\end_layout
\begin_layout Itemize
tensormultiply(a,b) --> None
\end_layout
\begin_layout Subsection
Additional Extension modules
\end_layout
\begin_layout Standard
There are three extension packages that come included with numarray which
are now downloaded separately.
Stubs for these packages exist in numpy.numarray but they try and find the
actual code by looking at what is currently installed.
These packages are available in SciPy but can be installed separately as
well:
\end_layout
\begin_layout Itemize
nd_image --> scipy.ndimage
\end_layout
\begin_layout Itemize
convolve --> scipy.stsci.convolve
\end_layout
\begin_layout Itemize
image --> scipy.stsci.image
\end_layout
\begin_layout Standard
If you don't want to install all of scipy, you can grab just these packages
from SVN using
\end_layout
\begin_layout LyX-Code
svn co http://svn.scipy.org/svn/scipy/trunk/Lib/ndimage ndimage
\end_layout
\begin_layout LyX-Code
svn co http://svn.scipy.org/svn/scipy/trunk/Lib/stsci stsci
\end_layout
\begin_layout Standard
and then run
\end_layout
\begin_layout LyX-Code
cd ndimage; sudo python setup.py install
\end_layout
\begin_layout LyX-Code
cd stsci; sudo python setup.py install
\end_layout
\begin_layout Standard
On a Windows system, you can use the Tortoise SVN client which is integrated
into the Windows Explorer.
It can be downloaded from http://tortoisesvn.tigris.org.
Instructions on how to use it are also provided on that site.
After downloading the packages from SVN, installation will still require
a C-compiler (the mingw32 compiler works fine even with MSVC-compiled Python
as long as you specify --compiler=mingw32).
Alternatively you can download binary releases of scipy from http://www.scipy.org
to get the needed functionality or use the Enthon edition of Python.
\end_layout
\begin_layout Chapter
The Array Object
\end_layout
\begin_layout Quotation
Don't worry about people stealing your ideas.
If your ideas are any good, you'll have to ram them down people's throats.
\end_layout
\begin_layout Right Address
---
\emph on
Howard Aiken, IBM engineer
\end_layout
\begin_layout Quotation
No idea is so antiquated that it was not once modern; no idea is so modern
that it will not someday be antiquated.
\end_layout
\begin_layout Right Address
---
\emph on
Ellen Glasgow
\end_layout
\begin_layout Section
\family typewriter
ndarray
\family default
Attributes
\end_layout
\begin_layout Standard
Array
\begin_inset LatexCommand index
name "ndarray|("
\end_inset
attributes reflect information that is intrinsic to the array itself.
Generally, accessing an array through its attributes allows you to get
and sometimes set intrinsic properties of the array without creating a
new array.
The exposed attributes are the core parts of an array and only some of
them can be reset meaningfully without creating a new array.
Table
\begin_inset LatexCommand ref
reference "cap:ndarray-attributes"
\end_inset
shows all the attributes
\begin_inset LatexCommand index
name "ndarray!attributes|("
\end_inset
with a brief description.
Detailed information on each attribute is given below.
\end_layout
\begin_layout Warning
Numeric Compatibility: you should check your old use of the .flat attribute.
This attribute now returns an iterator object which acts like a 1-d array
in terms of indexing.
while it does not share all the attributes or methods of an array, it will
be interpreted as an array in functions that take objects and convert them
to arrays.
Furthermore, Any changes in an array converted from a 1-d iterator will
be reflected back in the original array when the converted array is deleted.
\end_layout
\begin_layout Standard
\begin_inset Float table
wide false
sideways false
status open
\begin_layout Standard
\begin_inset Caption
\begin_layout Standard
\begin_inset LatexCommand label
name "cap:ndarray-attributes"
\end_inset
Attributes of the
\family typewriter
ndarray
\family default
.
\end_layout
\end_inset
\end_layout
\begin_layout Standard
\begin_inset ERT
status collapsed
\begin_layout Standard
\backslash
vspace*{-0.2in}
\backslash
setlength{
\backslash
extrarowheight}{0.25eM}
\end_layout
\begin_layout Standard
\end_layout
\begin_layout Standard
\end_layout
\end_inset
\end_layout
\begin_layout Standard
\align center
\begin_inset Tabular
\begin_inset Text
\begin_layout Standard
\family sans
\series bold
\size large
Attribute
\end_layout
\end_inset
|
\begin_inset Text
\begin_layout Standard
\family sans
\series bold
\size large
Settable
\end_layout
\end_inset
|
\begin_inset Text
\begin_layout Standard
\family sans
\series bold
\size large
Description
\end_layout
\end_inset
|
\begin_inset Text
\begin_layout Standard
\series bold
flags
\end_layout
\end_inset
|
\begin_inset Text
\begin_layout Standard
No
\end_layout
\end_inset
|
\begin_inset Text
\begin_layout Standard
special array-connected dictionary-like object with attributes showing the
state of flags in this array; only the flags WRITEABLE, ALIGNED, and UPDATEIFCO
PY can be modified by setting attributes of this object
\end_layout
\end_inset
|
\begin_inset Text
\begin_layout Standard
\series bold
shape
\end_layout
\end_inset
|
\begin_inset Text
\begin_layout Standard
Yes
\end_layout
\end_inset
|
\begin_inset Text
\begin_layout Standard
tuple showing the array shape; setting this attribute re-shapes the array
\end_layout
\end_inset
|
\begin_inset Text
\begin_layout Standard
\series bold
strides
\end_layout
\end_inset
|
\begin_inset Text
\begin_layout Standard
Yes
\end_layout
\end_inset
|
\begin_inset Text
\begin_layout Standard
tuple showing how many
\emph on
bytes
\emph default
must be jumped in the data segment to get from one entry to the next
\end_layout
\end_inset
|
\begin_inset Text
\begin_layout Standard
\series bold
ndim
\end_layout
\end_inset
|
\begin_inset Text
\begin_layout Standard
No
\end_layout
\end_inset
|
\begin_inset Text
\begin_layout Standard
number of dimensions in array
\end_layout
\end_inset
|
\begin_inset Text
\begin_layout Standard
\series bold
data
\end_layout
\end_inset
|
\begin_inset Text
\begin_layout Standard
Yes
\end_layout
\end_inset
|
\begin_inset Text
\begin_layout Standard
buffer object loosely wrapping the array data (only works for single-segment
arrays)
\end_layout
\end_inset
|
\begin_inset Text
\begin_layout Standard
\series bold
size
\end_layout
\end_inset
|
\begin_inset Text
\begin_layout Standard
No
\end_layout
\end_inset
|
\begin_inset Text
\begin_layout Standard
total number of elements
\end_layout
\end_inset
|
\begin_inset Text
\begin_layout Standard
\series bold
itemsize
\end_layout
\end_inset
|
\begin_inset Text
\begin_layout Standard
No
\end_layout
\end_inset
|
\begin_inset Text
\begin_layout Standard
size (in bytes) of each element
\end_layout
\end_inset
|
\begin_inset Text
\begin_layout Standard
\series bold
nbytes
\end_layout
\end_inset
|
\begin_inset Text
\begin_layout Standard
No
\end_layout
\end_inset
|
\begin_inset Text
\begin_layout Standard
total number of bytes used
\end_layout
\end_inset
|
\begin_inset Text
\begin_layout Standard
\series bold
base
\end_layout
\end_inset
|
\begin_inset Text
\begin_layout Standard
No
\end_layout
\end_inset
|
\begin_inset Text
\begin_layout Standard
object this array is using for its data buffer, or None if it owns its own
memory
\end_layout
\end_inset
|
\begin_inset Text
\begin_layout Standard
\series bold
dtype
\end_layout
\end_inset
|
\begin_inset Text
\begin_layout Standard
Yes
\end_layout
\end_inset
|
\begin_inset Text
\begin_layout Standard
data-type object for this array
\end_layout
\end_inset
|
\begin_inset Text
\begin_layout Standard
\series bold
real
\end_layout
\end_inset
|
\begin_inset Text
\begin_layout Standard
Yes
\end_layout
\end_inset
|
\begin_inset Text
\begin_layout Standard
real part of the array; setting copies data to real part of current array
\end_layout
\end_inset
|
\begin_inset Text
\begin_layout Standard
\series bold
imag
\end_layout
\end_inset
|
\begin_inset Text
\begin_layout Standard
Yes
\end_layout
\end_inset
|
\begin_inset Text
\begin_layout Standard
imaginary part, or read-only zero array if type is not complex; setting
works only if type is complex
\end_layout
\end_inset
|
\begin_inset Text
\begin_layout Standard
\series bold
flat
\end_layout
\end_inset
|
\begin_inset Text
\begin_layout Standard
Yes
\end_layout
\end_inset
|
\begin_inset Text
\begin_layout Standard
one-dimensional, indexable iterator object that acts somewhat like a 1-d
array
\end_layout
\end_inset
|
\begin_inset Text
\begin_layout Standard
\series bold
ctypes
\end_layout
\end_inset
|
\begin_inset Text
\begin_layout Standard
No
\end_layout
\end_inset
|
\begin_inset Text
\begin_layout Standard
object to simplify the interaction of this array with the ctypes module
\end_layout
\end_inset
|
\begin_inset Text
\begin_layout Standard
\series bold
__array_interface__
\end_layout
\end_inset
|
\begin_inset Text
\begin_layout Standard
No
\end_layout
\end_inset
|
\begin_inset Text
\begin_layout Standard
dictionary with keys (data, typestr, descr, shape, strides) for compliance
with Python side of array protocol
\end_layout
\end_inset
|
\begin_inset Text
\begin_layout Standard
\series bold
__array_struct__
\end_layout
\end_inset
|
\begin_inset Text
\begin_layout Standard
No
\end_layout
\end_inset
|
\begin_inset Text
\begin_layout Standard
array interface on C-level
\end_layout
\end_inset
|
\begin_inset Text
\begin_layout Standard
\series bold
__array_priority__
\end_layout
\end_inset
|
\begin_inset Text
\begin_layout Standard
No
\end_layout
\end_inset
|
\begin_inset Text
\begin_layout Standard
always 0.0 for base type
\family typewriter
ndarray
\end_layout
\end_inset
|
\end_inset
\end_layout
\end_inset
\end_layout
\begin_layout Subsection
Memory Layout attributes
\end_layout
\begin_layout Description
flags
\begin_inset LatexCommand index
name "ndarray!attributes!flags"
\end_inset
\end_layout
\begin_layout Description
\InsetSpace ~
Array flags
\begin_inset LatexCommand index
name "ndarray!flags|("
\end_inset
provide information about how the memory area used for the array is to
be interpreted.
There are 6 Boolean flags in use which govern whether or not:
\end_layout
\begin_deeper
\begin_layout Description
C_CONTIGUOUS\InsetSpace ~
(C) the data is in a single, C-style contiguous segment;
\end_layout
\begin_layout Description
F_CONTIGUOUS\InsetSpace ~
(F) the data is in a single, Fortran-style contiguous segment;
\end_layout
\begin_layout Description
OWNDATA\InsetSpace ~
(O) the array owns the memory it uses or if it borrows it from another
object (if this is False, the base attribute retrieves a reference to the
object this array obtained its data from);
\end_layout
\begin_layout Description
WRITEABLE\InsetSpace ~
(W) the data area can be written to;
\end_layout
\begin_layout Description
ALIGNED\InsetSpace ~
(A) the data and strides are aligned appropriately for the hardware
(as determined by the compiler);
\end_layout
\begin_layout Description
UPDATEIFCOPY\InsetSpace ~
(U) this array is a copy of some other array (referenced by
\family typewriter
.base
\family default
).
When this array is deallocated, the base array will be updated with the
contents of this array.
\end_layout
\end_deeper
\begin_layout Description
\InsetSpace ~
Only the
\series bold
UPDATEIFCOPY
\series default
,
\series bold
WRITEABLE
\series default
, and
\series bold
ALIGNED
\series default
flags can be changed by the user.
This can be done using the special array-connected, dictionary-like object
that the flags attribute returns.
By setting elements in this dictionary, the underlying array obect's flags
are altered.
Flags can also be changed using the method
\family typewriter
setflags
\family default
(...).
All flags in the dictionary can be accessed using their first (upper case)
letter as well as the full name.
\end_layout
\begin_layout Description
\InsetSpace ~
Certain logical combinations of flags can also be read using named keys
to the special flags dictionary.
These combinations are
\end_layout
\begin_deeper
\begin_layout Description
FNC Returns F_CONTIGUOUS and not C_CONTIGUOUS
\end_layout
\begin_layout Description
FORC Returns F_CONTIGUOUS or C_CONTIGUOUS (one-segment test).
\end_layout
\begin_layout Description
BEHAVED\InsetSpace ~
(B) Returns ALIGNED and WRITEABLE
\end_layout
\begin_layout Description
CARRAY\InsetSpace ~
(CA) Returns BEHAVED and C_CONTIGUOUS
\end_layout
\begin_layout Description
FARRAY_(FA) Returns BEHAVED and F_CONTIGUOUS and not C_CONTIGUOUS
\end_layout
\end_deeper
\begin_layout Note
The array flags cannot be set arbitrarily.
UPDATEIFCOPY can only be set False.
the ALIGNED flag can only be set True if the data is truly aligned.
The flag WRITEABLE can only be set True if the array owns its own memory
or the ultimate owner of the memory exposes a writeable buffer interface
(or is a string).
The exception for string is made so that unpickling can be done without
copying memory.
\end_layout
\begin_layout Description
\InsetSpace ~
Flags can also be set and read using attribute access with the lower-case
key equivalent (without first letter support).
Thus, for example, self.flags.c_contiguous returns whether or not the array
is C-style contiguous, and self.flags.writeable=True changes the array to
be writeable (if possible)
\begin_inset LatexCommand index
name "ndarray!flags|)"
\end_inset
.
\end_layout
\begin_layout Description
shape
\begin_inset LatexCommand index
name "ndarray!attributes!shape"
\end_inset
\end_layout
\begin_layout Description
\InsetSpace ~
The shape of the array is a tuple giving the number of elements in each
dimension.
The shape can be reset for single-segment arrays by setting this attribute
to another tuple.
The total number of elements cannot change.
However, a -1 may be used in a dimension entry to indicate that the array
length in that dimension should be computed so that the total number of
elements does not change.
\family typewriter
a.shape=x
\family default
is equivalent to
\family typewriter
a=a.reshape(x)
\family default
except the latter can be used even if the array is not single-segment and
even if
\begin_inset Formula $a$
\end_inset
is an array scalar.
\end_layout
\begin_layout Note
Setting the shape attribute to () for a 1-element array will turn self into
a 0-dimensional array.
This is one of the few ways to get a 0-dimensional array in Python.
Most other operations will return an array scalar.
Other ways to get a 0-dimensional array in Python include calling array
with a scalar argument and calling the squeeze method of an array whose
shape is all 1's.
\end_layout
\begin_layout Description
strides
\begin_inset LatexCommand index
name "ndarray!attributes!strides"
\end_inset
\end_layout
\begin_layout Description
\InsetSpace ~
The strides of an array is a tuple showing for each dimension how many
\emph on
bytes
\emph default
must be skipped to get to the next element in that dimension.
Setting this attribute to another tuple will change the way the memory
is viewed.
This attribute can only be set to a tuple that will not cause the array
to access unavailable memory.
If an attempt is made to do so, ValueError is raised.
\end_layout
\begin_layout Description
ndim
\begin_inset LatexCommand index
name "ndarray!attributes!ndim"
\end_inset
\end_layout
\begin_layout Description
\InsetSpace ~
The number of dimensions of an array is sometimes called the rank of the
array.
Getting this attribute reveals the length of the shape tuple and the strides
tuple.
\end_layout
\begin_layout Description
data
\begin_inset LatexCommand index
name "ndarray!attributes!data"
\end_inset
\end_layout
\begin_layout Description
\InsetSpace ~
A buffer object referencing the actual data for this array if this array
is single-segment.
If the array is not single-segment, then an AttributeError is raised.
The buffer object is writeable depending on the status of self.flags.writeable.
\end_layout
\begin_layout Description
size
\begin_inset LatexCommand index
name "ndarray!attributes!size"
\end_inset
\end_layout
\begin_layout Description
\InsetSpace ~
The total number of elements in the array.
\end_layout
\begin_layout Description
itemsize
\begin_inset LatexCommand index
name "ndarray!attributes!itemsize"
\end_inset
\end_layout
\begin_layout Description
\InsetSpace ~
The number of bytes each element of the array requires.
\end_layout
\begin_layout Description
nbytes
\begin_inset LatexCommand index
name "ndarray!attributes!nbytes"
\end_inset
\end_layout
\begin_layout Description
\InsetSpace ~
The total number of bytes used by the array.
This is equal to
\family typewriter
self.itemsize*self.size
\family default
.
\end_layout
\begin_layout Description
base
\begin_inset LatexCommand index
name "ndarray!attributes!base"
\end_inset
\end_layout
\begin_layout Description
\InsetSpace ~
If the array does not own its own memory, then this attribute returns the
object whose memory this array is referencing.
The returned object may not be the original allocator of the memory, but
may be borrowing it from still another object.
If this array does own its own memory, then None is returned unless the
UPDATEIFCOPY flag is True in which case self.base is the array that will
be updated when self is deleted.
UPDATEIFCOPY gets set for an array that is created as a behaved copy of
a general array.
The intent is for the misaligned array to get any changes that occur to
the copy.
\end_layout
\begin_layout Subsection
Data Type attributes
\end_layout
\begin_layout Standard
There are several ways to specify the kind of data that the array is composed
of.
The fullest description that preserves field information is always obtained
using an actual dtype object.
See Chapter
\begin_inset LatexCommand ref
reference "cha:Data-descriptor-objects"
\end_inset
for more discussion on data-type objects and acceptable arguments to construct
data-type objects.
Three commonly-used attributes of the data-type object returned are also
documented here.
\end_layout
\begin_layout Description
dtype
\begin_inset LatexCommand index
name "ndarray!attributes!dtype"
\end_inset
\end_layout
\begin_layout Description
\InsetSpace ~
A data-type object that fully describes (including any defined fields)
each fixed-length item in the array.
Whether or not the data is in machine byte-order is also determined by
the data-type.
The data-type attribute can be set to anything that can be interpreted
as a data-type (see Chapter
\begin_inset LatexCommand ref
reference "cha:Data-descriptor-objects"
\end_inset
for more information).
Setting this attribute allows you to change the interpretation of the data
in the array.
The new data-type must be compatible with the array's current data-type.
The new data-type is compatible if it has the same itemsize as the current
data-type descriptor, or (if the array is a single-segment array) if the
the array with the new data-type fits in the memory already consumed by
the array.
\end_layout
\begin_layout Description
dtype.type
\end_layout
\begin_layout Description
\InsetSpace ~
A Python type object gives the typeobject whose instances represent elements
of the array.
This type object can be used to instantiate a scalar of that type.
\end_layout
\begin_layout Description
dtype.char
\end_layout
\begin_layout Description
\InsetSpace ~
A typecode character unique to each of the 21 built-in types.
\end_layout
\begin_layout Description
dtype.str
\end_layout
\begin_layout Description
\InsetSpace ~
This string consists of a required first character giving the
\begin_inset Quotes eld
\end_inset
endianness
\begin_inset Quotes erd
\end_inset
of the data (
\begin_inset Quotes eld
\end_inset
<
\begin_inset Quotes erd
\end_inset
for little endian,
\begin_inset Quotes eld
\end_inset
>
\begin_inset Quotes erd
\end_inset
for big endian, and
\begin_inset Quotes eld
\end_inset
|
\begin_inset Quotes erd
\end_inset
for irrelevant), the second character is a code for the kind of data ('b'
for Boolean, 'i' for signed integer, 'u' for unsigned integer, 'f' for
floating-point, 'c' for complex floating point, 'O' for object, 'S' for
ASCII string, 'U' for unicode, and 'V' for void), the final characters
give the number of bytes each element uses.
\end_layout
\begin_layout Subsection
Other attributes
\end_layout
\begin_layout Description
T
\begin_inset LatexCommand index
name "ndarray!attributes!T"
\end_inset
\end_layout
\begin_layout Description
\InsetSpace ~
Equivalent to self.transpose().
For self.ndim < 2, it returns a view of self.
\end_layout
\begin_layout Warning
If arr is 0- or 1-dimensional, then arr.T will return a new ndarray which
refers to the same data as arr.
This is because transpose has the effect of reversing the shape attribute
of an array (whose 0-d and 1-d equivalent is to return the same array).
This may be surprising if you are thinking of your 1-d array as a
\begin_inset Quotes eld
\end_inset
row
\begin_inset Quotes erd
\end_inset
or a
\begin_inset Quotes eld
\end_inset
column
\begin_inset Quotes erd
\end_inset
vector and expected the .T attribute to return the other convention.
\end_layout
\begin_layout Description
real
\begin_inset LatexCommand index
name "ndarray!attributes!real"
\end_inset
\end_layout
\begin_layout Description
\InsetSpace ~
The real part of an array.
For arrays that are not complex this attribute returns the array itself.
Setting this attribute allows setting just the real part of an array.
If the array is already real then setting this attribute is equivalent
to self[...] = values.
\end_layout
\begin_layout Description
imag
\begin_inset LatexCommand index
name "ndarray!attributes!imag"
\end_inset
\end_layout
\begin_layout Description
\InsetSpace ~
A view of the imaginary part of an array.
For arrays that are not complex, this returns a read-only array of zeros.
Setting this array allows in-place alteration of the complex part of an
imaginary array.
If the array is not complex, then trying to set this attribute raises an
Error.
\end_layout
\begin_layout Description
flat
\begin_inset LatexCommand index
name "ndarray!attributes!flat"
\end_inset
\end_layout
\begin_layout Description
\InsetSpace ~
Return an iterator object (numpy.flatiter) that acts like a 1-d version
of the array.
1-d indexing works on this array and it can be passed in to most routines
as an array wherein a 1-d array will be constructed from it.
The new 1-d array will reference this array's data if this array is C-style
contiguous, otherwise, new memory will be allocated for the 1-d array,
the UPDATEIFCOPY flag will be set for the new array, and this array will
have its WRITEABLE flag set FALSE until the the last reference to the new
array disappears.
When the last reference to the new 1-d array disappears, the data will
be copied over to this non-contiguous array.
This is done so that a.flat effectively references the current array regardless
of whether or not it is contiguous or non-contiguous.
As an example, consider the following code:
\end_layout
\begin_layout MyCode
>>> a = zeros((4,5))
\newline
>>> b = ones(6)
\newline
>>> add(b,b,a[1:3,0:3].flat)
\newline
array([[ 2.,
2., 2.],
\newline
[ 2., 2., 2.]])
\newline
>>> print a
\newline
[[ 0.
0.
0.
0.
0.]
\newline
[ 2.
2.
2.
0.
0.]
\newline
[ 2.
2.
2.
0.
0.]
\newline
[ 0.
0.
0.
0.
0.]]
\end_layout
\begin_layout Description
\InsetSpace ~
The numpy.flatiter object has two methods:
\series bold
__array__()
\series default
and
\series bold
copy()
\series default
and one attribute:
\series bold
base
\series default
.
The base attribute returns a reference to the underlying array.
\end_layout
\begin_layout Description
__array_priority__
\begin_inset LatexCommand index
name "ndarray!attributes!\\_\\_array\\_priority\\_\\_"
\end_inset
\end_layout
\begin_layout Description
\InsetSpace ~
The array priority attribute is a floating point number useful in mixed
operations involving two subtypes to decide which subtype is returned.
The base ndarray object has priority 0.0 and 1.0 is the default subtype priority.
\end_layout
\begin_layout Subsection
Array Interface attributes
\end_layout
\begin_layout Standard
The array interface
\begin_inset LatexCommand index
name "array interface"
\end_inset
(sometimes called array protocol) was created in 2005 as a means for array-like
Python objects to re-use each other's data buffers intelligently whenever
possible.
The ndarray object supports both the Python-side and the C-side of the
array interface.
The system is able to consume objects that expose the array interface,
and array objects can expose their inner workings to other objects that
support the array interface.
\end_layout
\begin_layout Description
__array_interface__
\begin_inset LatexCommand index
name "ndarray!attributes!\\_\\_array\\_interface\\_\\_"
\end_inset
\end_layout
\begin_layout Description
\InsetSpace ~
The python-side of the array interface.
It is a dictionary with the following attributes:
\end_layout
\begin_deeper
\begin_layout Description
data A 2-tuple (dataptr, read-only flag).
The dataptr is a string giving the address (in hexadecimal format) of the
array data.
The read-only flag is True if the array memory is read-only.
\end_layout
\begin_layout Description
strides The strides tuple.
Same as
\series bold
strides
\series default
attribute except None is returned if the array is C-style contiguous.
\end_layout
\begin_layout Description
shape The shape tuple.
Same as
\series bold
shape
\series default
attribute.
\end_layout
\begin_layout Description
typestr A string giving the format of the data.
Same as
\series bold
dtype.str
\series default
attribute.
\end_layout
\begin_layout Description
descr A list of tuples providing the detailed description of this data type.
This information is obtained from the arrdescr attribute of the dtypedescr
object associated with each array.
For arrays with fields, this will return a valid array-protocol descriptor
list.
For arrays without defined fields, this returns [('',typestr)].
\end_layout
\end_deeper
\begin_layout Description
__array_struct__
\begin_inset LatexCommand index
name "ndarray!attributes!\\_\\_array\\_struct\\_\\_"
\end_inset
\end_layout
\begin_layout Description
\InsetSpace ~
A PyCObject that wraps a pointer to a PyArrayInterface structure.
This is only useful on the C-level for rapid implementation of the array
interface, using a single attribute lookup.
\end_layout
\begin_layout Description
ctypes
\begin_inset LatexCommand index
name "ndarray!attributes!ctypes|("
\end_inset
\end_layout
\begin_layout Description
\InsetSpace ~
This attribute creates an object that makes it easier to use arrays when
calling out to shared libraries with the ctypes module.
The returned object has data, shape, and strides attributes which return
ctypes
\begin_inset LatexCommand index
name "ctypes"
\end_inset
objects that can be used as arguments to a shared library.
These attributes are:
\end_layout
\begin_deeper
\begin_layout Description
data A pointer to the memory area of the array as a Python integer.
This memory area may contain data that is not aligned, or not in correct
byte-order.
The memory area may not even be writeable.
The array flags and data-type of this array should be respected when passing
this attribute to arbitrary C-code to avoid trouble that can include Python
crashing.
User Beware! The value of this attribute is exactly the same as
\family typewriter
self.__array_interface__['data'][0]
\family default
.
\end_layout
\begin_layout Description
shape (c_intp*self.ndim) A ctypes array of length self.ndim where the base-type
is the C-integer corresponding to dtype('p') on this platform.
This base-type could be c_int, c_long, or c_longlong depending on the platform.
The c_intp type is defined accordingly in numpy.ctypeslib.
The ctypes array contains the shape of the underlying array.
\end_layout
\begin_layout Description
strides (c_intp*self.ndim) A ctypes array of length self.ndim where the base-type
is the same as for the shape attribute.
This ctypes array contains the strides information from the underlying
array.
This strides information is important for showing how many bytes must be
jumped to get to the next element in the array.
\end_layout
\begin_layout Description
_as_parameter_ (c_void_p) Returns the data-pointer to the array as a ctypes
object.
Among other possible uses, this enables this ctypes object to be used directly
in a ctypes-loaded call to an arbitrary function.
Be sure to respect the flags on the array and the size and strides of the
array so as not to use this memory in-appropriately (see the
\series bold
ndpointer
\series default
function for how to return a class that can be used with the argtypes attribute
of ctypes functions).
\end_layout
\end_deeper
\begin_layout Warning
Be careful using the ctypes attribute --- especially on temporary arrays
or arrays constructed on the fly.
For example, calling (a+b).ctypes.data_as(ctypes.c_void_p) returns a pointer
to memory that is invalid because the array created as (a+b) is deallocated
before the next Python statement.
You can avoid this problem using either c=a+b or ct=(a+b).ctypes.
In the latter case, ct will hold a reference to the array until ct is deleted
or re-assigned.
\end_layout
\begin_layout Description
\InsetSpace ~
The ctypes object also has several methods which can alter how the shape,
strides, and data of the underlying object is returned.
\end_layout
\begin_deeper
\begin_layout Description
data_as (obj) Return the data pointer cast-to a particular c-types object.
For example, calling
\family typewriter
self._as_parameter_
\family default
is equivalent to
\family typewriter
self.data_as(ctypes.c_void_p)
\family default
.
Perhaps you want to use the data as a pointer to a ctypes array of floating-poi
nt data:
\family typewriter
self.data_as(ctypes.POINTER(ctypes.c_double))
\family default
.
\end_layout
\begin_layout Description
shape_as (obj) Return the shape tuple as an array of some other c-types
type.
For example:
\family typewriter
self.shape_as(ctypes.c_short)
\family default
.
\end_layout
\begin_layout Description
strides_as (obj) Return the strides tuple as an array of some other c-types
type.
For example:
\family typewriter
self.strides_as(ctypes.c_longlong)
\family default
.
\end_layout
\end_deeper
\begin_layout Description
\InsetSpace ~
If the ctypes module is not available, then the ctypes attribute of array
objects still returns something useful, but ctypes objects are not returned
and errors may be raised instead.
In particular, the object will still have the _as_parameter_ attribute
which will return an integer equal to the data
\begin_inset LatexCommand index
name "ndarray!attributes!ctypes|)"
\end_inset
attribute
\begin_inset LatexCommand index
name "ndarray!attributes|)"
\end_inset
.
\end_layout
\begin_layout Section
\family typewriter
ndarray
\family default
Methods
\end_layout
\begin_layout Standard
In NumPy, the
\family typewriter
ndarray
\family default
object has many methods
\begin_inset LatexCommand index
name "ndarray!methods|("
\end_inset
which operate on or with the array in some fashion, typically returning
an array result.
In Numeric, many of these methods were only library calls.
These methods are explained in this chapter.
Whenever the array whose method is being called needs to be referenced
it will be referred to as
\emph on
this array
\emph default
, or
\emph on
self
\emph default
.
Keyword arguments will be shown.
Methods that only take one argument do not have keyword arguments.
Default values for one argument methods will be shown in braces {default}.
\end_layout
\begin_layout Warning
If you are converting code from Numeric, then you will need to make the
following (search and replace) conversions:
\family typewriter
.typecode() --> .dtype.char
\family default
;
\family typewriter
.iscontiguous() --> .flags.contiguous
\family default
;
\family typewriter
.byteswapped() --> .byteswap()
\family default
;
\family typewriter
.toscalar() --> .item()
\family default
; and
\family typewriter
.itemsize() --> .itemsize
\family default
.
The numpy.oldnumeric.alter_code1 module can automate this for you.
\end_layout
\begin_layout Subsection
Array conversion
\end_layout
\begin_layout Description
tolist
\begin_inset LatexCommand index
name "ndarray!methods!tolist"
\end_inset
()
\end_layout
\begin_layout Description
\InsetSpace ~
The contents of self as a nested list.
\end_layout
\begin_layout MyCode
>>> a = array([[1,2,3],[4,5,6]]); print a.tolist()
\newline
[[1, 2, 3], [4, 5, 6]]
\end_layout
\begin_layout Description
item
\begin_inset LatexCommand index
name "ndarray!methods!item"
\end_inset
(*args)
\end_layout
\begin_layout Description
\InsetSpace ~
If no arguments are passed in, then this method only works for arrays with
one element (a.size == 1).
In this case, it returns a standard Python scalar object (if possible)
copied from the first element of self.
When the data type of self is longdouble or clongdouble, this returns a
scalar array object because there is no available Python scalar that would
not lose information.
Void arrays return a buffer object for item() unless fields are defined
in which case a tuple is returned.
\end_layout
\begin_layout MyCode
>>> asc = a[0,0].item()
\newline
>>> type(asc)
\newline
\newline
>>> asc
\newline
1
\newline
>>> type(a[0,0])
\newline
\end_layout
\begin_layout Description
\InsetSpace ~
If arguments are provided, then they indicate indices into the array (either
a flat index or an nd-index).
A standard Python scalar corresponding to the item at the given location
is then returned.
This is very similar to self[args] except instead of an array scalar, a
standard Python scalar is returned.
This can be useful for speeding up access to elements of the array and
doing arithmetic on elements of the array using Python's optimized math.
\end_layout
\begin_layout Description
itemset
\begin_inset LatexCommand index
name "ndarray!methods!itemset"
\end_inset
(*args)
\end_layout
\begin_layout Description
\InsetSpace ~
There must be at least 1 argument and define the last argument as item.
Then, this is equivalent to but faster than self[args] = item.
The item should be a scalar value and args must select a single item in
the array.
\end_layout
\begin_layout Description
tostring
\begin_inset LatexCommand index
name "ndarray!methods!tostring"
\end_inset
(order='C')
\end_layout
\begin_layout Description
\InsetSpace ~
A Python string showing a copy of the raw contents of data memory.
The string can be produced in either 'C' or 'Fortran', or 'Any' order (the
default is 'C'-order).
'Any' order means C-order unless the F_CONTIGUOUS flag in the array is
set, then 'Fortran' order.
\end_layout
\begin_layout Description
tofile
\begin_inset LatexCommand index
name "ndarray!methods!tofile"
\end_inset
(file=, sep='', format='')
\end_layout
\begin_layout Description
\InsetSpace ~
Write the contents of self to the open file object.
If file is a string, then open a file of that name first.
If sep is the empty string, then write the file in binary mode.
If sep is any other string, write the array in simple text mode separating
each element with the value of the sep string.
When the file is written in text mode, the format string can be used to
alter the appearance of each entry.
If format is the empty string, then it is equivalent to
\family typewriter
\begin_inset Quotes eld
\end_inset
%s
\begin_inset Quotes erd
\end_inset
\family default
.
Each element of the array will be converted to a Python scalar,
\family typewriter
o
\family default
, and written to the file as
\family typewriter
\begin_inset Quotes eld
\end_inset
format
\begin_inset Quotes erd
\end_inset
% o
\family default
.
Note that writing an array to a file does not store any information about
the shape, type, or endianness of an array.
When written in binary mode, tofile is functionally equivalent to
\family typewriter
fid.write(self.tostring())
\family default
.
\end_layout
\begin_layout MyCode
>>> a.tofile('myfile.txt',sep=':',format='%03d')
\end_layout
\begin_layout MyCode
Contents of myfile.txt
\end_layout
\begin_layout MyCode
001:002:003:004:005:006
\end_layout
\begin_layout Description
dump
\begin_inset LatexCommand index
name "ndarray!methods!dump"
\end_inset
(file)
\end_layout
\begin_layout Description
\InsetSpace ~
Pickle the contents of self to the file object represented by file.
Equivalent to cPickle.dump(self, file, 2)
\end_layout
\begin_layout Description
dumps
\begin_inset LatexCommand index
name "ndarray!methods!dumps"
\end_inset
()
\end_layout
\begin_layout Description
\InsetSpace ~
Return pickled representation of self as a string.
Equivalent to cPickle.dumps(self, 2)
\end_layout
\begin_layout Description
astype
\begin_inset LatexCommand index
name "ndarray!methods!astype"
\end_inset
({None})
\end_layout
\begin_layout Description
\InsetSpace ~
Force conversion of this array to an array with the data type provided
as the argument.
If the argument is None, or equal to the data type of self, then return
a copy of the array.
\end_layout
\begin_layout Description
byteswap
\begin_inset LatexCommand index
name "ndarray!methods!byteswap"
\end_inset
({False})
\end_layout
\begin_layout Description
\InsetSpace ~
Byteswap the elements of the array and return the byteswapped array.
If the argument is True, then byteswap in-place and return a reference
to self.
Otherwise, return a copy of the array with the elements byteswapped.
The data-type descriptor is not changed so the array will have changed
numbers.
\end_layout
\begin_layout Description
copy
\begin_inset LatexCommand index
name "ndarray!methods!copy"
\end_inset
()
\end_layout
\begin_layout Description
\InsetSpace ~
Return a copy of the array (which is always single-segment, and ALIGNED).
However, the data-type is preserved (including whether or not the data
is byteswapped).
\end_layout
\begin_layout Description
view
\begin_inset LatexCommand index
name "ndarray!methods!view"
\end_inset
({None})
\end_layout
\begin_layout Description
\InsetSpace ~
Return a new array using the same memory area as self.
If the optional argument is given, it can be either a typeobject that is
a sub-type of the ndarray or an object that can be converted to a data-type
descriptor.
If the argument is a typeobject then a new array of that Python type is
returned that uses the information from self.
If the argument is a data-type descriptor, then a new array of the same
Python type as self is returned using the given data-type.
\end_layout
\begin_layout MyCode
>>> print a.view(single)
\newline
[[ 1.40129846e-45 2.80259693e-45 4.20389539e-45]
\newline
[ 5.60519386e-45 7.00649232e-45 8.40779079e-45]]
\newline
>>> a.view(ubyte)
\newline
array([[1,
0, 0, 0, 2, 0, 0, 0, 3, 0, 0, 0],
\newline
[4, 0, 0, 0, 5, 0, 0, 0, 6, 0,
0, 0]], dtype=uint8)
\end_layout
\begin_layout Description
getfield
\begin_inset LatexCommand index
name "ndarray!methods!getfield"
\end_inset
(dtype=, offset=0)
\end_layout
\begin_layout Description
\InsetSpace ~
Return a
\emph on
field
\emph default
of the given array as an array of the given data type.
A field is a view of the array's data at a certain byte offset interpreted
as a given data type.
The returned array is a reference into self, therefore changes made to
the returned array will be reflected in self.
This method is particularly useful for record arrays that use a void data
type, but it can also be used to extract the low (high)-order bytes of
other array types as well.
For example, using getfield, you could extract fixed-length substrings
from an array of strings.
\end_layout
\begin_layout MyCode
>>> a = array(['Hello','World','NumPy'])
\newline
>>> a.getfield('S2',1)
\newline
array(['el',
'or', 'um'],
\newline
dtype='|S2')
\end_layout
\begin_layout Description
setflags
\begin_inset LatexCommand index
name "ndarray!methods!setflags"
\end_inset
(write=None, align=None, uic=None)
\end_layout
\begin_layout Description
\InsetSpace ~
Set array flags WRITEABLE, ALIGNED, and UPDATEIFCOPY, respectively.
The ALIGNED flag can only be set to True if the data is actually aligned
according to the type.
The UPDATEIFCOPY flag can never be set to True.
The flag WRITEABLE can only be set True if the array owns its own memory
or the ultimate owner of the memory exposes a writeable buffer interface
(or is a string).
The exception for string is made so that unpickling can be done without
copying memory.
\end_layout
\begin_layout Description
fill
\begin_inset LatexCommand index
name "ndarray!methods!fill"
\end_inset
(scalar)
\end_layout
\begin_layout Description
\InsetSpace ~
Fill an array with the scalar value (appropriately converted to the type
of self).
If the scalar value is an array or a sequence, then only the first element
is used.
This method is usually faster than a[...]=scalar or self.flat=scalar, and always
interprets its argument as a scalar.
\end_layout
\begin_layout Standard
\begin_inset Float table
wide false
sideways false
status open
\begin_layout Standard
\begin_inset Caption
\begin_layout Standard
Array conversion methods
\end_layout
\end_inset
\end_layout
\begin_layout Standard
\begin_inset ERT
status collapsed
\begin_layout Standard
\backslash
setlength{
\backslash
extrarowheight}{0.1eM}
\end_layout
\begin_layout Standard
\end_layout
\begin_layout Standard
\end_layout
\end_inset
\end_layout
\begin_layout Standard
\align center
\begin_inset Tabular
\begin_inset Text
\begin_layout Standard
\family sans
\series bold
\size large
Method
\end_layout
\end_inset
|
\begin_inset Text
\begin_layout Standard
\family sans
\series bold
\size large
Arguments
\end_layout
\end_inset
|
\begin_inset Text
\begin_layout Standard
\family sans
\series bold
\size large
Description
\end_layout
\end_inset
|
\begin_inset Text
\begin_layout Standard
\series bold
astype
\end_layout
\end_inset
|
\begin_inset Text
\begin_layout Standard
(dtype {None})
\end_layout
\end_inset
|
\begin_inset Text
\begin_layout Standard
Cast to another data type
\end_layout
\end_inset
|
\begin_inset Text
\begin_layout Standard
\series bold
byteswap
\end_layout
\end_inset
|
\begin_inset Text
\begin_layout Standard
(inplace {False})
\end_layout
\end_inset
|
\begin_inset Text
\begin_layout Standard
Byteswap array elements
\end_layout
\end_inset
|
\begin_inset Text
\begin_layout Standard
\series bold
copy
\end_layout
\end_inset
|
\begin_inset Text
\begin_layout Standard
()
\end_layout
\end_inset
|
\begin_inset Text
\begin_layout Standard
Copy array
\end_layout
\end_inset
|
\begin_inset Text
\begin_layout Standard
\series bold
dump
\end_layout
\end_inset
|
\begin_inset Text
\begin_layout Standard
(file)
\end_layout
\end_inset
|
\begin_inset Text
\begin_layout Standard
Pickle to stream or file
\end_layout
\end_inset
|
\begin_inset Text
\begin_layout Standard
\series bold
dumps
\end_layout
\end_inset
|
\begin_inset Text
\begin_layout Standard
()
\end_layout
\end_inset
|
\begin_inset Text
\begin_layout Standard
Get pickled string
\end_layout
\end_inset
|
\begin_inset Text
\begin_layout Standard
\series bold
fill
\end_layout
\end_inset
|
\begin_inset Text
\begin_layout Standard
(scalar)
\end_layout
\end_inset
|
\begin_inset Text
\begin_layout Standard
Fill an array with scalar value
\end_layout
\end_inset
|
\begin_inset Text
\begin_layout Standard
\series bold
getfield
\end_layout
\end_inset
|
\begin_inset Text
\begin_layout Standard
(dtype=, offset=0)
\end_layout
\end_inset
|
\begin_inset Text
\begin_layout Standard
Return a field of the array
\end_layout
\end_inset
|
\begin_inset Text
\begin_layout Standard
\series bold
setflags
\end_layout
\end_inset
|
\begin_inset Text
\begin_layout Standard
(write=None, align=None, uic=None)
\end_layout
\end_inset
|
\begin_inset Text
\begin_layout Standard
Set array flags
\end_layout
\end_inset
|
\begin_inset Text
\begin_layout Standard
\series bold
tofile
\end_layout
\end_inset
|
\begin_inset Text
\begin_layout Standard
(file=, sep='', format='')
\end_layout
\end_inset
|
\begin_inset Text
\begin_layout Standard
Raw write to file
\end_layout
\end_inset
|
\begin_inset Text
\begin_layout Standard
\series bold
tolist
\end_layout
\end_inset
|
\begin_inset Text
\begin_layout Standard
()
\end_layout
\end_inset
|
\begin_inset Text
\begin_layout Standard
Array as a nested list
\end_layout
\end_inset
|
\begin_inset Text
\begin_layout Standard
\series bold
item
\end_layout
\end_inset
|
\begin_inset Text
\begin_layout Standard
(*args)
\end_layout
\end_inset
|
\begin_inset Text
\begin_layout Standard
Python scalar extraction
\end_layout
\end_inset
|
\begin_inset Text
\begin_layout Standard
\series bold
itemset
\end_layout
\end_inset
|
\begin_inset Text
\begin_layout Standard
(*args)
\end_layout
\end_inset
|
\begin_inset Text
\begin_layout Standard
Insert scalar (last argument) into array
\end_layout
\end_inset
|
\begin_inset Text
\begin_layout Standard
\series bold
tostring
\end_layout
\end_inset
|
\begin_inset Text
\begin_layout Standard
(order='C')
\end_layout
\end_inset
|
\begin_inset Text
\begin_layout Standard
String of raw memory
\end_layout
\end_inset
|
\begin_inset Text
\begin_layout Standard
\series bold
view
\end_layout
\end_inset
|
\begin_inset Text
\begin_layout Standard
(obj)
\end_layout
\end_inset
|
\begin_inset Text
\begin_layout Standard
View as another data type or class
\end_layout
\end_inset
|
\end_inset
\end_layout
\end_inset
\end_layout
\begin_layout Subsection
Array shape manipulation
\end_layout
\begin_layout Standard
For reshape, resize, and transpose, the single tuple argument may be replaced
with
\begin_inset Formula $n$
\end_inset
integers which will be interpreted as an
\begin_inset Formula $n$
\end_inset
-tuple.
\end_layout
\begin_layout Description
reshape
\begin_inset LatexCommand index
name "ndarray!methods!reshape"
\end_inset
(newshape, order='C')
\end_layout
\begin_layout Description
\InsetSpace ~
Return an array that uses the same data as this array but has a new shape
given by the newshape tuple (or a scalar to reshape as 1-d).
The new shape must define an array with the same total number of elements.
If one of the elements of the new shape tuple is -1, then that dimension
will be determined such that the overall number of items in the array stays
constant.
If possible, the new array will reference the data of the old one.
If the data must be moved in order to accomplish the reshape, then then
the new array will contain a copy of the data in self.
The order argument specifies how the array data should be viewed during
the reshape (either in 'C' or 'FORTRAN' order).
This order argument specifies both how the intrinsic raveling to a 1-d
array should occur as well as how that 1-d array should be used to fill-up
the new output array.
\end_layout
\begin_layout Description
resize
\begin_inset LatexCommand index
name "ndarray!methods!resize"
\end_inset
(newshape, refcheck=1, order='C')
\end_layout
\begin_layout Description
\InsetSpace ~
Resize an array in-place.
This changes self (in-place) to be an array with the new shape, reallocating
space for the data area if necessary.
If the data memory must be changed because the number of new elements is
different than self.size, then an error will occur if this array does not
own its data or if another object is referencing this one.
Only a single-segment array can be resized.
The method returns None.
To bypass the reference count check, then set refcheck=0.
The purpose of the reference count check is to make sure you don't use
this array as a buffer for another Python object and then reallocate the
memory.
However, reference counts can increase in other ways so if you are sure
that you have not shared the memory for this array to another Python object,
then you may safely set refcheck=0.
\end_layout
\begin_layout Description
transpose
\begin_inset LatexCommand index
name "ndarray!methods!transpose"
\end_inset
()
\end_layout
\begin_layout Description
\InsetSpace ~
Return an array view with the shape transposed according to the argument.
An argument of None is equivalent to range(self.ndim)[::-1].
The argument can either be a tuple or multiple integer arguments.
This method returns a new array with permuted shape and strides attributes
using the same data as self.
\end_layout
\begin_layout MyCode
>>> a = arange(40).reshape((2,4,5))
\newline
>>> b = a.transpose(2,0,1)
\newline
>>> print a.shape,
b.shape
\newline
(2, 4, 5) (5, 2, 4)
\newline
>>> print a.strides, b.strides
\newline
(80, 20, 4) (4, 80,
20)
\newline
>>> print a
\newline
[[[ 0 1 2 3 4]
\newline
[ 5 6 7 8 9]
\newline
[10 11 12 13 14]
\newline
[15
16 17 18 19]]
\newline
\newline
[[20 21 22 23 24]
\newline
[25 26 27 28 29]
\newline
[30 31 32 33 34]
\newline
[35
36 37 38 39]]]
\newline
>>> print b
\newline
[[[ 0 5 10 15]
\newline
[20 25 30 35]]
\newline
\newline
[[ 1 6 11 16]
\newline
[21 26 31 36]]
\newline
\newline
[[ 2 7 12 17]
\newline
[22 27 32 37]]
\newline
\newline
[[ 3 8 13 18]
\newline
[23 28 33
38]]
\newline
\newline
[[ 4 9 14 19]
\newline
[24 29 34 39]]]
\end_layout
\begin_layout Description
swapaxes
\begin_inset LatexCommand index
name "ndarray!methods!swapaxes"
\end_inset
(axis1, axis2)
\end_layout
\begin_layout Description
\InsetSpace ~
Return an array view with axis1 and axis2 swapped.
This is a special case of the transpose method with argument equal to arg=range
(self.ndim); arg[axis1], arg[axis2] = arg[axis2], arg[axis1].
See the
\series bold
rollaxis
\series default
function for a routine that transposes the array with the axes rolled instead
of swapped.
\end_layout
\begin_layout Description
flatten
\begin_inset LatexCommand index
name "ndarray!methods!flatten"
\end_inset
(order='C')
\end_layout
\begin_layout Description
\InsetSpace ~
Return a new 1-d array with data copied from self.
Equivalent to but slightly faster then a.flat.copy().
\end_layout
\begin_layout Description
ravel
\begin_inset LatexCommand index
name "ndarray!methods!ravel"
\end_inset
(order='C')
\end_layout
\begin_layout Description
\InsetSpace ~
Return a 1-d version of self.
If self is single-segment, then the new array references self, otherwise,
a copy is made.
\end_layout
\begin_layout Description
squeeze
\begin_inset LatexCommand index
name "ndarray!methods!squeeze"
\end_inset
()
\end_layout
\begin_layout Description
\InsetSpace ~
Return an array with all unit-length dimensions squeezed out.
\end_layout
\begin_layout Subsection
Array item selection and manipulation
\end_layout
\begin_layout Standard
For array methods that take an axis keyword, it defaults to None.
If axis is None, then the array is treated as a 1-D array.
Any other value for axis represents the dimension along which the operation
should proceed.
\end_layout
\begin_layout Description
take
\begin_inset LatexCommand index
name "ndarray!methods!take"
\end_inset
(indices=, axis=None, out=None, mode='raise')
\end_layout
\begin_layout Description
\InsetSpace ~
The functionality of this method is available using the advanced indexing
ability of the
\family typewriter
ndarray
\family default
object.
However, for doing selection along a single axis it is usually faster to
use take.
If axis is not None, this method is equivalent to
\family typewriter
self[indxobj]
\family default
preceeded by
\family typewriter
indxobj=[slice(None)]*self.ndim; indxobj[
\series bold
axis
\series default
] =
\family default
\family typewriter
\series bold
indices
\family default
\series default
.
It returns the elements or sub-arrays from self indicated by the index
numbers in indices.
If axis is None, then this method is equivalent to
\family typewriter
self.flat[indices]
\family default
.
The out and mode arguments allow for specification of the output array
and how out-of-bounds indices will be handled ('raise': raise an error,
'wrap': wrap around, 'clip': clip to range)
\end_layout
\begin_layout Description
put
\begin_inset LatexCommand index
name "ndarray!methods!put"
\end_inset
(indices=, values=, mode='raise')
\end_layout
\begin_layout Description
\InsetSpace ~
Performs the equivalent of
\end_layout
\begin_layout LyX-Code
for n in
\series bold
indices
\series default
:
\end_layout
\begin_layout LyX-Code
self.flat[n] =
\series bold
values
\series default
[n]
\end_layout
\begin_layout Description
\InsetSpace ~
Values is repeated if it is too short.
The mode argument specifies what to do if n is too large.
\end_layout
\begin_layout Description
repeat
\begin_inset LatexCommand index
name "ndarray!methods!repeat"
\end_inset
(repeats=, axis=None)
\end_layout
\begin_layout Description
\InsetSpace ~
Copy elements (or sub-arrays selected along axis) of self
\series bold
repeats
\series default
times.
The repeats argument must be a sequence of length self.shape[axis] or a
scalar.
The repeats argument dictates how many times the element (or sub-array)
will be repeated in the result array.
\end_layout
\begin_layout Description
choose
\begin_inset LatexCommand index
name "ndarray!methods!choose"
\end_inset
(choices, out=None, mode='raise')
\end_layout
\begin_layout Description
\InsetSpace ~
The array must be an integer (or bool) array with entries from
\begin_inset Formula $0$
\end_inset
to
\begin_inset Formula $n$
\end_inset
.
Choices is a tuple of
\begin_inset Formula $n$
\end_inset
choice arrays:
\begin_inset Formula $b0,\, b1,\,\ldots\,,\, bn$
\end_inset
.
(Alternatively, choices can be replaced with
\begin_inset Formula $n$
\end_inset
arguments where each argument is a choice array).
The return array will be formed from the elements of the choice arrays
according to the value of the elements of self.
In other words, the output array will merge the choice arrays together
by using the value of self at a particular position to select which choice
array should be used for the output at a particular position.
The out keyword allows specification of an output array and the clip keyword
allows different behavior when self contains entries outside the number
of choices.
The acceptable arguments to mode are 'raise' (RAISE), 'wrap' (WRAP), and
'clip' (CLIP) ('raise' produces an error, 'wrap' converts the number into
range by periodic wrapping so that numbers <0 have
\begin_inset Formula $n$
\end_inset
repeatedly added and numbers >=
\begin_inset Formula $n$
\end_inset
have
\begin_inset Formula $n$
\end_inset
repeatedly subtracted, and 'clip' will clip all entries to be within the
range [0,
\begin_inset Formula $n$
\end_inset
).
\end_layout
\begin_layout MyCode
>>> a = array([0,3,2,1])
\newline
>>> a.choose([0,1,2,3],[10,11,12,13],
\newline
...
[20,21,22,23],[30,31,32,33])
\newline
array([ 0, 31, 22, 13])
\end_layout
\begin_layout Description
sort
\begin_inset LatexCommand index
name "ndarray!methods!sort"
\end_inset
(axis=-1, kind='quick', order=None)
\end_layout
\begin_layout Description
\InsetSpace ~
Sort the array in-place and return None.
The sort takes place over the given axis using an underlying sort algorithm
specified by kind.
The sorting algorithms available are 'quick', 'heap', and 'merge'.
For flexible types only the quicksort algorithm is available.
For arrays with fields defined, the order keyword allows specification
of the order in which to use the field names in the sort.
If order is a string then it is the field name to use to define the sort.
If order is a list (or tuple) of strings, then it specifies a lexicographic
ordering so that the first listed field name is compared first if that
results in equality, the second listed field name is used for the comparison
and so on.
If order is None, then arrays with fields use the first field for comparison.
\end_layout
\begin_layout MyCode
>>> a=array([[0.2,1.3,2.5],[1.5,0.1,1.4]]);
\newline
>>> b=a.copy(); b.sort(0); print b
\newline
[[
0.2 0.1 1.4]
\newline
[ 1.5 1.3 2.5]]
\newline
>>> b=a.copy(); b.sort(1); print b
\newline
[[ 0.2 1.3 2.5]
\newline
[ 0.1 1.4 1.5]]
\end_layout
\begin_layout Description
argsort
\begin_inset LatexCommand index
name "ndarray!methods!argsort"
\end_inset
(axis=-1, kind='quick', order=None)
\end_layout
\begin_layout Description
\InsetSpace ~
Return an index array of the same size as self showing which indices along
the given axis should be selected to sort self along that axis.
Uses an underlying sort algorithm specified by kind.
The sorting algorithms available are 'quick', 'heap', and 'merge'.
For arrays with fields defined, the order keyword allows specification
of the order in which to use the field names in the sort.
If order is a string then it is the field name to use to define the sort.
If order is a list (or tuple) of strings, then it specifies a lexicographic
ordering so that the first listed field name is compared first if that
results in equality, the second listed field name is used for the comparison
and so on.
If order is None, then arrays with fields use the first field for comparison.
\end_layout
\begin_layout MyCode
>>> b=a.copy(); print b.argsort(0)
\newline
[[0 1 1]
\newline
[1 0 0]]
\newline
>>> b=a.copy(); print b.argsort(1
)
\newline
[[0 1 2]
\newline
[1 2 0]]
\end_layout
\begin_layout Tip
Complex valued arrays sort lexicographically by comparing first the real
parts and then the imaginary parts if the real parts are the same.
\end_layout
\begin_layout Description
searchsorted
\begin_inset LatexCommand index
name "ndarray!methods!searchsorted"
\end_inset
(values, side='left')
\end_layout
\begin_layout Description
\InsetSpace ~
Return an index array (dtype=intp) of the same shape as values showing
the index where the value would fit in self.
The index is such that self[index-1]
\begin_inset Formula $<$
\end_inset
value
\begin_inset Formula $\le$
\end_inset
self[index] when side is 'left'.
In this formula self[self.size]=
\begin_inset Formula $\infty$
\end_inset
and self[-1]=
\begin_inset Formula $-\infty$
\end_inset
.
Therefore, if value is larger than all elements of self, then index is
self.size.
If value is smaller than all elements of self, then index is 0.
Self must be a sorted 1-d array.
If elements of self are repeated, the index of the first occurrence is
used.
If side is 'right', then the search rule is switched so that the
\begin_inset Formula $<$
\end_inset
sign is on the
\begin_inset Quotes eld
\end_inset
right
\begin_inset Quotes erd
\end_inset
instead of the left in the search rule.
In other words, the index returned is such that self[index-1]
\begin_inset Formula $\le$
\end_inset
value
\begin_inset Formula $<$
\end_inset
self[index].
\end_layout
\begin_layout MyCode
>>> b=a.ravel(); b.sort()
\newline
>>> b.searchsorted([0.0, 1.35, 2.0, 3.0])
\newline
array([0, 3,
5, 6])
\end_layout
\begin_layout Description
nonzero
\begin_inset LatexCommand index
name "ndarray!methods!nonzero"
\end_inset
()
\end_layout
\begin_layout Description
\InsetSpace ~
Return the
\begin_inset Formula $n$
\end_inset
-dimensional indices for elements of the
\begin_inset Formula $n$
\end_inset
-dimensional array self that are nonzero into an
\begin_inset Formula $n$
\end_inset
-tuple of equal-length index arrays.
In particular, notice that a 0-dimensional array always returns an empty
tuple.
\end_layout
\begin_layout MyCode
>>> x = arange(15); y=x.reshape(3,5)
\newline
>>> (x>8).nonzero()
\newline
(array([ 9, 10, 11,
12, 13, 14]),)
\newline
>>> (y>8).nonzero()
\newline
(array([1, 2, 2, 2, 2, 2]), array([4, 0,
1, 2, 3, 4]))
\end_layout
\begin_layout Description
compress
\begin_inset LatexCommand index
name "ndarray!methods!compress"
\end_inset
(condition=, axis=None, out=None)
\end_layout
\begin_layout Description
\InsetSpace ~
This method expects condition to be a one-dimensional mask array of the
same length as self.shape[axis].
If the array is less than self.shape[axis], then False is assumed for the
missing elements.
The method returns the elements (or sub-arrays along the given axis) of
self where condition is true.
The shape of the return array is self.shape with the axis dimension replaced
by the number of True elements of condition.
The same effect can often be accomplished using array indexing.
\end_layout
\begin_layout MyCode
>>> x=array([0,1,2,3])
\newline
>>> x.compress(x > 2)
\newline
array([3])
\newline
>>> x[x>2]
\newline
array([3])
\end_layout
\begin_layout Description
diagonal
\begin_inset LatexCommand index
name "ndarray!methods!diagonal"
\end_inset
(offset=0, axis1=0, axis2=1)
\end_layout
\begin_layout Description
\InsetSpace ~
If self is 2-d, return the
\series bold
offset
\series default
(from the main diagonal) diagonal of self.
If self is larger than 2-d, then return an array constructed from all the
diagonals created from all the 2-d sub-arrays formed using all of axis1
and axis2.
The offset parameter is with respect to axis2.
The shape of the returned array is found by removing the axis1 and axis2
entries from self.shape and then appending the length of the offset diagonal
of each 2-d sub-array.
\end_layout
\begin_layout MyCode
>>> a=arange(25).reshape(5,5); print a
\newline
[[ 0 1 2 3 4]
\newline
[ 5 6 7 8 9]
\newline
[10 11 12 13 14]
\newline
[15 16 17 18 19]
\newline
[20 21 22 23 24]]
\newline
>>> print a.diagonal()
\newline
[
0 6 12 18 24]
\newline
>>> print a.diagonal(1)
\newline
[ 1 7 13 19]
\newline
>>> print a.diagonal(-1)
\newline
[
5 11 17 23]
\end_layout
\begin_layout Standard
\begin_inset Float table
wide false
sideways false
status open
\begin_layout Standard
\begin_inset Caption
\begin_layout Standard
Array item selection and shape manipulation methods.
If axis is an argument, then the calculation is performed along that axis.
An axis value of None means the array is flattened before calculation proceeds.
\end_layout
\end_inset
\end_layout
\begin_layout Standard
\begin_inset ERT
status collapsed
\begin_layout Standard
\backslash
setlength{
\backslash
extrarowheight}{0.25eM}
\end_layout
\begin_layout Standard
\end_layout
\begin_layout Standard
\end_layout
\end_inset
\end_layout
\begin_layout Standard
\align center
\begin_inset Tabular
\begin_inset Text
\begin_layout Standard
\family sans
\series bold
\size large
Method
\end_layout
\end_inset
|
\begin_inset Text
\begin_layout Standard
\family sans
\series bold
\size large
Arguments
\end_layout
\end_inset
|
\begin_inset Text
\begin_layout Standard
\family sans
\series bold
\size large
Description
\end_layout
\end_inset
|
\begin_inset Text
\begin_layout Standard
\series bold
argsort
\end_layout
\end_inset
|
\begin_inset Text
\begin_layout Standard
argsort (axis=None, kind='quick')
\end_layout
\end_inset
|
\begin_inset Text
\begin_layout Standard
Indices showing how to sort array.
\end_layout
\end_inset
|
\begin_inset Text
\begin_layout Standard
\series bold
choose
\end_layout
\end_inset
|
\begin_inset Text
\begin_layout Standard
choose (c0, c1 , ..., cn, out=None, clip='raise')
\end_layout
\end_inset
|
\begin_inset Text
\begin_layout Standard
Choose from different arrays based on value of self.
\end_layout
\end_inset
|
\begin_inset Text
\begin_layout Standard
\series bold
compress
\end_layout
\end_inset
|
\begin_inset Text
\begin_layout Standard
(condition=, axis=None, out=None)
\end_layout
\end_inset
|
\begin_inset Text
\begin_layout Standard
Elements of self where condition is true.
\end_layout
\end_inset
|
\begin_inset Text
\begin_layout Standard
\series bold
diagonal
\end_layout
\end_inset
|
\begin_inset Text
\begin_layout Standard
(offset=0, axis1=0, axis2=1)
\end_layout
\end_inset
|
\begin_inset Text
\begin_layout Standard
Return a diagonal from self.
\end_layout
\end_inset
|
\begin_inset Text
\begin_layout Standard
\series bold
flatten
\end_layout
\end_inset
|
\begin_inset Text
\begin_layout Standard
(order='C')
\end_layout
\end_inset
|
\begin_inset Text
\begin_layout Standard
A 1-d copy of self.
\end_layout
\end_inset
|
\begin_inset Text
\begin_layout Standard
\series bold
nonzero
\end_layout
\end_inset
|
\begin_inset Text
\begin_layout Standard
()
\end_layout
\end_inset
|
\begin_inset Text
\begin_layout Standard
True where self is not zero.
\end_layout
\end_inset
|
\begin_inset Text
\begin_layout Standard
\series bold
put
\end_layout
\end_inset
|
\begin_inset Text
\begin_layout Standard
(indices=, values=, mode='raise')
\end_layout
\end_inset
|
\begin_inset Text
\begin_layout Standard
Place values at 1-d index locations of self.
\end_layout
\end_inset
|
\begin_inset Text
\begin_layout Standard
\series bold
ravel
\end_layout
\end_inset
|
\begin_inset Text
\begin_layout Standard
(order='C')
\end_layout
\end_inset
|
\begin_inset Text
\begin_layout Standard
1-d version of self (no data copy if self is C-style contiguous).
\end_layout
\end_inset
|
\begin_inset Text
\begin_layout Standard
\series bold
repeat
\end_layout
\end_inset
|
\begin_inset Text
\begin_layout Standard
(repeats=, axis=None)
\end_layout
\end_inset
|
\begin_inset Text
\begin_layout Standard
Repeat elements of self.
\end_layout
\end_inset
|
\begin_inset Text
\begin_layout Standard
\series bold
reshape
\end_layout
\end_inset
|
\begin_inset Text
\begin_layout Standard
(d1,d2,...,dn, order='C')
\end_layout
\end_inset
|
\begin_inset Text
\begin_layout Standard
Return reshaped version of self.
\end_layout
\end_inset
|
\begin_inset Text
\begin_layout Standard
\series bold
resize
\end_layout
\end_inset
|
\begin_inset Text
\begin_layout Standard
(d1,d2,...,dn, refcheck=1, order='Any')
\end_layout
\end_inset
|
\begin_inset Text
\begin_layout Standard
Resize self in-place.
\end_layout
\end_inset
|
\begin_inset Text
\begin_layout Standard
\series bold
searchsorted
\end_layout
\end_inset
|
\begin_inset Text
\begin_layout Standard
(values)
\end_layout
\end_inset
|
\begin_inset Text
\begin_layout Standard
Show where values would be placed in self (assumed sorted).
\end_layout
\end_inset
|
\begin_inset Text
\begin_layout Standard
\series bold
sort
\end_layout
\end_inset
|
\begin_inset Text
\begin_layout Standard
(axis=None, kind='quick')
\end_layout
\end_inset
|
\begin_inset Text
\begin_layout Standard
Copy of self sorted along axis.
\end_layout
\end_inset
|
\begin_inset Text
\begin_layout Standard
\series bold
squeeze
\end_layout
\end_inset
|
\begin_inset Text
\begin_layout Standard
()
\end_layout
\end_inset
|
\begin_inset Text
\begin_layout Standard
Squeeze out all length-1 dimensions.
\end_layout
\end_inset
|
\begin_inset Text
\begin_layout Standard
\series bold
swapaxes
\end_layout
\end_inset
|
\begin_inset Text
\begin_layout Standard
(axis1, axis2)
\end_layout
\end_inset
|
\begin_inset Text
\begin_layout Standard
Swap two dimensions of self.
\end_layout
\end_inset
|
\begin_inset Text
\begin_layout Standard
\series bold
take
\end_layout
\end_inset
|
\begin_inset Text
\begin_layout Standard
(indices=, axis=None, out=None, mode='raise')
\end_layout
\end_inset
|
\begin_inset Text
\begin_layout Standard
Select elements of self along axis according to indices.
\end_layout
\end_inset
|
\begin_inset Text
\begin_layout Standard
\series bold
transpose
\end_layout
\end_inset
|
\begin_inset Text
\begin_layout Standard
(permute )
\end_layout
\end_inset
|
\begin_inset Text
\begin_layout Standard
Rearrange shape of self according to permute.
\end_layout
\end_inset
|
\end_inset
\end_layout
\end_inset
\end_layout
\begin_layout Subsection
Array calculation
\end_layout
\begin_layout Standard
Many of these methods take an argument named axis.
In such cases, if axis is None (the default), the array is treated as a
1-d array and the operation is performed over the entire array.
This behavior is also the default if self is a 0-dimensional array or array
scalar.
If axis is an integer, then the operation is done over the given axis (for
each 1-d subarray that can be created along the given axis).
The parameter dtype specifies the data type over which a reduction operation
(like summing) should take place.
The default reduce data type is the same as the data type of self.
To avoid overflow, it can be useful to perform the reduction using a larger
data type.
For several methods, an optional out argument can be provided and the result
will be placed into the output array given.
The out argument must be an ndarray and have the same number of elements.
It can be of a different type in which case casting will be performed.
\end_layout
\begin_layout Description
max
\begin_inset LatexCommand index
name "ndarray!methods!max"
\end_inset
(axis=None, out=None)
\end_layout
\begin_layout Description
\InsetSpace ~
Return the largest value in self.
This is a better way to compute the maximum over an array, than using max(self).
The latter uses the generic sequence interface to self.
This will be slower, and will try to get an answer by comparing whole sub-array
s of self.
This will be incorrect for arrays larger than 1-d.
\end_layout
\begin_layout Description
argmax
\begin_inset LatexCommand index
name "ndarray!methods!argmax"
\end_inset
(axis=None, out=None)
\end_layout
\begin_layout Description
\InsetSpace ~
Return the (first, 1-d) index of the largest value in self.
\end_layout
\begin_layout Description
min
\begin_inset LatexCommand index
name "ndarray!methods!min"
\end_inset
(axis=None, out=None)
\end_layout
\begin_layout Description
\InsetSpace ~
Return the smallest value in self.
This is a better way to compute the minimum over an array, than using min(self).
The latter uses the generic sequence interface to self.
This will be slower, and will try to get an answer by comparing whole sub-array
s of self.
This will be incorrect for arrays larger than 1-d.
\end_layout
\begin_layout Description
argmin
\begin_inset LatexCommand index
name "ndarray!methods!argmin"
\end_inset
(axis=None, out=None)
\end_layout
\begin_layout Description
\InsetSpace ~
Return the (first, 1-d) index of the smallest value in self.
\end_layout
\begin_layout Description
ptp
\begin_inset LatexCommand index
name "ndarray!methods!ptp"
\end_inset
(axis=None, out=None)
\end_layout
\begin_layout Description
\InsetSpace ~
Return the difference of the largest to the smallest value in self.
Equivalent to self.max(axis) - self.min(axis)
\end_layout
\begin_layout Description
clip
\begin_inset LatexCommand index
name "ndarray!methods!clip"
\end_inset
(min=,max=, out=None)
\end_layout
\begin_layout Description
\InsetSpace ~
Return a new array where any element in self less than min is set to min
and any element less than max is set to max.
Equivalent to self[selfmax]=max.
\end_layout
\begin_layout Description
conj
\begin_inset LatexCommand index
name "ndarray!methods!conj"
\end_inset
(out=None)
\end_layout
\begin_layout Description
conjugate
\begin_inset LatexCommand index
name "ndarray!methods!conjugate"
\end_inset
(out=None)
\end_layout
\begin_layout Description
\InsetSpace ~
Return the conjugate of elements of the array.
\end_layout
\begin_layout Description
round
\begin_inset LatexCommand index
name "ndarray!methods!round"
\end_inset
(decimals=0, out=None)
\end_layout
\begin_layout Description
\InsetSpace ~
Round the elements of the array to the nearest decimal.
For decimals < 0, the rounding is done to the nearest tens, hundreds, etc.
Rounding of exactly the half-interval is to the nearest even integer.
This is the only difference with standard Python rounding.
\end_layout
\begin_layout Description
trace
\begin_inset LatexCommand index
name "ndarray!methods!trace"
\end_inset
(offset=0, axis1=0, axis2=1, dtype=None, out=None)
\end_layout
\begin_layout Description
\InsetSpace ~
Perform a summation along each diagonal specified by offset, axis1, and
axis2.
Equivalent to diagonal(offset,axis1,axis2).sum(axis=-1, dtype=dtype)
\end_layout
\begin_layout Description
sum
\begin_inset LatexCommand index
name "ndarray!methods!sum"
\end_inset
(axis=None, dtype=None, out=None)
\end_layout
\begin_layout Description
\InsetSpace ~
Return the sum
\begin_inset Formula \[
\sum_{i=0}^{N-1}\textrm{self}[\underbrace{:,\ldots,:}_{\textrm{axis}},i]\]
\end_inset
where axis ':' objects are placed before the
\begin_inset Formula $i.$
\end_inset
\end_layout
\begin_layout Description
cumsum
\begin_inset LatexCommand index
name "ndarray!methods!cumsum"
\end_inset
(axis=None, dtype=None, out=None)
\end_layout
\begin_layout Description
\InsetSpace ~
Return the cumulative sum.
If ret is the return array of the same shape as
\begin_inset Formula $\textrm{self},$
\end_inset
then
\begin_inset Formula \[
\textrm{ret}[\underbrace{:,\ldots,:}_{\textrm{axis}},j]=\sum_{i=0}^{j}\textrm{self}[\underbrace{:,\ldots,:}_{\textrm{axis}},i].\]
\end_inset
\end_layout
\begin_layout Description
mean
\begin_inset LatexCommand index
name "ndarray!methods!mean"
\end_inset
(axis=None, dtype=None, out=None)
\end_layout
\begin_layout Description
\InsetSpace ~
Return the average value caculated as
\begin_inset Formula \[
\frac{1}{N}\sum_{i=0}^{N-1}\textrm{self}[\underbrace{:,\ldots,:}_{\textrm{axis}},i]\]
\end_inset
where
\begin_inset Formula $N$
\end_inset
is self.shape[axis] and axis ':' objects are placed before the
\begin_inset Formula $i.$
\end_inset
The sum is done in the data-type of self unless self is an integer or Boolean
data-type and then it is done over the float data-type.
\end_layout
\begin_layout Description
var
\begin_inset LatexCommand index
name "ndarray!methods!var"
\end_inset
(axis=None, dtype=None, out=None)
\end_layout
\begin_layout Description
\InsetSpace ~
Return the variance of the data calculated as
\begin_inset Formula \[
\frac{1}{N}\sum_{i=0}^{N-1}\left(\textrm{self}[\underbrace{:,\ldots,:}_{\textrm{axis}},i]-\mu\right)^{2}\]
\end_inset
where
\begin_inset Formula $N$
\end_inset
is self.shape[axis] and
\begin_inset Formula $\mu$
\end_inset
is the mean (restored to the same number of dimensions as self with
\begin_inset Formula $\mu$
\end_inset
copied along the axis dimension).
This is equivalent to (self**2).mean - self.mean()**2 and ((self-self.mean())**2).m
ean().
The value of
\begin_inset Formula $N-1$
\end_inset
was not chosen for normalization because while it gives an
\begin_inset Quotes eld
\end_inset
unbiased
\begin_inset Quotes erd
\end_inset
estimate, it is not always prudent to return unbiased estimates as they
may have larger mean-square error.
The sum is done using a float data-type if self has integer or Boolean
data-type, otherwise it is done using the same data-type as self.
\end_layout
\begin_layout Description
std
\begin_inset LatexCommand index
name "ndarray!methods!std"
\end_inset
(axis=None, dtype=None, out=None)
\end_layout
\begin_layout Description
\InsetSpace ~
Return the standard deviation calculated as
\begin_inset Formula \[
\sqrt{\frac{1}{N}\sum_{i=0}^{N-1}\left(\textrm{self}[\underbrace{:,\ldots,:}_{\textrm{axis}},i]-\mu\right)^{2}}\]
\end_inset
where
\begin_inset Formula $N$
\end_inset
is self.shape[axis] and
\begin_inset Formula $\mu$
\end_inset
is the mean (restored to the same number of dimensions as self with
\begin_inset Formula $\mu$
\end_inset
copied along the axis dimension).
The sum is done using the same data-type as self unless self is an integer
or Boolean data-type and then it is done using a float data-type.
\end_layout
\begin_layout Description
prod
\begin_inset LatexCommand index
name "ndarray!methods!prod"
\end_inset
(axis=None, dtype=None, out=None)
\end_layout
\begin_layout Description
\InsetSpace ~
Return the product calculated as
\begin_inset Formula \[
\prod_{i=0}^{N-1}\textrm{self}[\underbrace{:,\ldots,:}_{\textrm{axis}},i].\]
\end_inset
\end_layout
\begin_layout Description
cumprod
\begin_inset LatexCommand index
name "ndarray!methods!cumprod"
\end_inset
(axis=None, dtype=None, out=None)
\end_layout
\begin_layout Description
\InsetSpace ~
Return the cumulative product so that the return array, ret, is the same
shape as self and
\begin_inset Formula \[
\textrm{ret}[\underbrace{:,\ldots,:}_{\textrm{axis}},j]=\prod_{i=0}^{j}\textrm{self}[\underbrace{:,\ldots,:}_{\textrm{axis}},i].\]
\end_inset
\end_layout
\begin_layout Description
all
\begin_inset LatexCommand index
name "ndarray!methods!all"
\end_inset
(axis=None, out=None)
\end_layout
\begin_layout Description
\InsetSpace ~
Return True if all entries along axis evaluate True, otherwise return False.
\end_layout
\begin_layout Description
any
\begin_inset LatexCommand index
name "ndarray!methods!any"
\end_inset
(axis=None, out=None)
\end_layout
\begin_layout Description
\InsetSpace ~
Return True if any entries along axis evaluate True, otherwise return False
\begin_inset LatexCommand index
name "ndarray!methods|)"
\end_inset
.
\end_layout
\begin_layout Standard
\begin_inset Float table
wide false
sideways false
status open
\begin_layout Standard
\begin_inset Caption
\begin_layout Standard
Array object calculation methods.
If axis is an argument, then the calculation is performed along that axis.
An axis value of None means the array is flattened before calculation proceeds.
All of these methods can take an optional out= argument which can specify
the output array to write the results into.
\end_layout
\end_inset
\end_layout
\begin_layout Standard
\begin_inset ERT
status collapsed
\begin_layout Standard
\backslash
setlength{
\backslash
extrarowheight}{0.5eM}
\end_layout
\begin_layout Standard
\end_layout
\begin_layout Standard
\end_layout
\end_inset
\end_layout
\begin_layout Standard
\align center
\begin_inset Tabular
\begin_inset Text
\begin_layout Standard
\family sans
\series bold
\size large
Method
\end_layout
\end_inset
|
\begin_inset Text
\begin_layout Standard
\family sans
\series bold
\size large
Arguments
\end_layout
\end_inset
|
\begin_inset Text
\begin_layout Standard
\family sans
\series bold
\size large
Description
\end_layout
\end_inset
|
\begin_inset Text
\begin_layout Standard
\series bold
all
\end_layout
\end_inset
|
\begin_inset Text
\begin_layout Standard
(axis=None)
\end_layout
\end_inset
|
\begin_inset Text
\begin_layout Standard
true if all entries are true.
\end_layout
\end_inset
|
\begin_inset Text
\begin_layout Standard
\series bold
any
\end_layout
\end_inset
|
\begin_inset Text
\begin_layout Standard
(axis=None)
\end_layout
\end_inset
|
\begin_inset Text
\begin_layout Standard
true if any entries are true.
\end_layout
\end_inset
|
\begin_inset Text
\begin_layout Standard
\series bold
argmax
\end_layout
\end_inset
|
\begin_inset Text
\begin_layout Standard
(axis=None)
\end_layout
\end_inset
|
\begin_inset Text
\begin_layout Standard
index of largest value.
\end_layout
\end_inset
|
\begin_inset Text
\begin_layout Standard
\series bold
argmin
\end_layout
\end_inset
|
\begin_inset Text
\begin_layout Standard
(axis=None)
\end_layout
\end_inset
|
\begin_inset Text
\begin_layout Standard
index of smallest value.
\end_layout
\end_inset
|
\begin_inset Text
\begin_layout Standard
\series bold
clip
\end_layout
\end_inset
|
\begin_inset Text
\begin_layout Standard
(min=, max=)
\end_layout
\end_inset
|
\begin_inset Text
\begin_layout Standard
self[self>max]=max; self[self
|
\begin_inset Text
\begin_layout Standard
\series bold
conj
\end_layout
\end_inset
|
\begin_inset Text
\begin_layout Standard
()
\end_layout
\end_inset
|
\begin_inset Text
\begin_layout Standard
complex conjugate
\end_layout
\end_inset
|
\begin_inset Text
\begin_layout Standard
\series bold
cumprod
\end_layout
\end_inset
|
\begin_inset Text
\begin_layout Standard
(axis=None, dtype=None)
\end_layout
\end_inset
|
\begin_inset Text
\begin_layout Standard
cumulative product
\end_layout
\end_inset
|
\begin_inset Text
\begin_layout Standard
\series bold
cumsum
\end_layout
\end_inset
|
\begin_inset Text
\begin_layout Standard
(axis=None, dtype=None)
\end_layout
\end_inset
|
\begin_inset Text
\begin_layout Standard
cumulative sum
\end_layout
\end_inset
|
\begin_inset Text
\begin_layout Standard
\series bold
max
\end_layout
\end_inset
|
\begin_inset Text
\begin_layout Standard
(axis=None)
\end_layout
\end_inset
|
\begin_inset Text
\begin_layout Standard
maximum of self
\end_layout
\end_inset
|
\begin_inset Text
\begin_layout Standard
\series bold
mean
\end_layout
\end_inset
|
\begin_inset Text
\begin_layout Standard
(axis=None, dtype=None)
\end_layout
\end_inset
|
\begin_inset Text
\begin_layout Standard
mean of self
\end_layout
\end_inset
|
\begin_inset Text
\begin_layout Standard
\series bold
min
\end_layout
\end_inset
|
\begin_inset Text
\begin_layout Standard
(axis=None)
\end_layout
\end_inset
|
\begin_inset Text
\begin_layout Standard
minimum of self
\end_layout
\end_inset
|
\begin_inset Text
\begin_layout Standard
\series bold
prod
\end_layout
\end_inset
|
\begin_inset Text
\begin_layout Standard
(axis=None, dtype=None)
\end_layout
\end_inset
|
\begin_inset Text
\begin_layout Standard
multiply elements of self together
\end_layout
\end_inset
|
\begin_inset Text
\begin_layout Standard
\series bold
ptp
\end_layout
\end_inset
|
\begin_inset Text
\begin_layout Standard
(axis=None)
\end_layout
\end_inset
|
\begin_inset Text
\begin_layout Standard
self.max(axis)-self.min(axis)
\end_layout
\end_inset
|
\begin_inset Text
\begin_layout Standard
\series bold
var
\end_layout
\end_inset
|
\begin_inset Text
\begin_layout Standard
(axis=None, dtype=None)
\end_layout
\end_inset
|
\begin_inset Text
\begin_layout Standard
variance of self
\end_layout
\end_inset
|
\begin_inset Text
\begin_layout Standard
\series bold
std
\end_layout
\end_inset
|
\begin_inset Text
\begin_layout Standard
(axis=None, dtype=None)
\end_layout
\end_inset
|
\begin_inset Text
\begin_layout Standard
standard deviation of self
\end_layout
\end_inset
|
\begin_inset Text
\begin_layout Standard
\series bold
sum
\end_layout
\end_inset
|
\begin_inset Text
\begin_layout Standard
(axis=None, dtype=None)
\end_layout
\end_inset
|
\begin_inset Text
\begin_layout Standard
add elements of self together
\end_layout
\end_inset
|
\begin_inset Text
\begin_layout Standard
\series bold
trace
\end_layout
\end_inset
|
\begin_inset Text
\begin_layout Standard
(offset, axis1=0, axis2=0, dtype=None)
\end_layout
\end_inset
|
\begin_inset Text
\begin_layout Standard
sum along a diagonal
\end_layout
\end_inset
|
\end_inset
\end_layout
\end_inset
\end_layout
\begin_layout Section
Array Special Methods
\end_layout
\begin_layout Standard
Methods
\begin_inset LatexCommand index
name "ndarray!special methods|("
\end_inset
in this chapter are not generally meant to be called directly by the user.
They are called by Python and are used to customize behavior of the ndarray
object as it interacts with the Python language and standard library.
\end_layout
\begin_layout Subsection
Methods for standard library functions
\end_layout
\begin_layout Description
__copy__
\begin_inset LatexCommand index
name "ndarray!special methods!copy"
\end_inset
()
\end_layout
\begin_layout Description
\InsetSpace ~
To allow copy.copy(a) to perform a shallow copy of an array.
Exactly the same as self.copy() (contents of object arrays are not copied).
\end_layout
\begin_layout Description
__deepcopy__
\begin_inset LatexCommand index
name "ndarray!special methods!deepcopy"
\end_inset
(memodict)
\end_layout
\begin_layout Description
\InsetSpace ~
To allow copy.deepcopy(a) to perform a deep copy.
This is the same as a shallow copy unless self is an object array.
Then, after the shallow copy is made, a copy.deepcopy(item) is called for
every item in the object array.
\end_layout
\begin_layout Description
__reduce__
\begin_inset LatexCommand index
name "ndarray!special methods!reduce"
\end_inset
()
\end_layout
\begin_layout Description
__setstate__
\begin_inset LatexCommand index
name "ndarray!special methods!setstate"
\end_inset
(shape, typestr, isfortran, data)
\end_layout
\begin_layout Description
\InsetSpace ~
Pickling support for arrays is provided by these two methods.
When an array needs to be pickled, the __reduce__() method is called to
provide a 3-tuple of already-pickleable objects.
To construct a new object from the pickle, the first two elements of the
3-tuple are used to construct a new (0-length) array of the correct type
and the last element of the 3-tuple, which is itself a 4-tuple of (shape,
typestr, isfortran, data) is passed to the __setstate__ method of the newly
created array to restore its contents.
\end_layout
\begin_layout Description
\InsetSpace ~
The reduce method returns a 3-tuple consisting of (callable, args, state)
where callable is a simple constructor function that handles subclasses
of the ndarray.
Also, args is a 3-tuple of arguments to pass to this constructor function
(type(self), (0,), self.dtypechar), and state is a 4-tuple of information
giving the object's state (self.shape, self.dtypedescr, isfortran, string_or_list
).
In this tuple, isfortran is a Bool stating whether the following flattened
data is in Fortran order or not, and string_or_list is a string formed
by self.tostring() if the data type is not object.
If the data type of self is an object array, then string_or_list is a flat
list equivalent to self.ravel().tolist().
\end_layout
\begin_layout Description
\InsetSpace ~
On load from a pickle, the pickling code uses the first two elements from
the tuple returned by reduce to construct an empty 0-dimensional subclass
of the correct type.
The last element is then passed to the __setstate__ method of the newly
created array to restore its contents.
\end_layout
\begin_layout Note
When data is a string, the __setstate__ method will directly use the string
memory as the array memory (new.base will point to the string).
The typestr contains enough information to decode how the memory should
be interpreted.
\end_layout
\begin_layout Subsection
Basic customization
\end_layout
\begin_layout Description
__new__
\begin_inset LatexCommand index
name "ndarray!special methods!new"
\end_inset
(subtype, shape=, dtype=long_, buffer=None, offset=0, strides=None, order=None)
\end_layout
\begin_layout Description
\InsetSpace ~
This method creates a new ndarray.
It is typically only used in the __new__ method of a subclass.
This method is called to construct a new array whenever the object name
is called,
\family typewriter
a=ndarray(...)
\family default
.
It supports two basic modes of array creation:
\end_layout
\begin_layout Enumerate
a single-segment array of the specified shape and data-type from newly allocated
memory;
\end_layout
\begin_deeper
\begin_layout Enumerate
uses shape, dtype, strides, and order arguments; others are ignored;
\end_layout
\begin_layout Enumerate
The order argument allows specification of a Fortran-style contiguous memory
segment (order='Fortran');
\end_layout
\begin_layout Enumerate
If strides is given, then it specifies the new strides of the array (and
the order keyword is ignored).
The strides will be checked for consistency with the dimension size so
that steps outside of the memory won't occur.
\end_layout
\end_deeper
\begin_layout Enumerate
an array of the given shape and data type using the provided object, buffer,
which must export the buffer interface.
\end_layout
\begin_deeper
\begin_layout Enumerate
all arguments can be used;
\end_layout
\begin_layout Enumerate
strides can be given and will be checked for consistency with the shape,
data type, and available memory in buffer;
\end_layout
\begin_layout Enumerate
order indicates whether the data buffer should be interpreted as Fortran-style
contiguous (order='Fortran') or not;
\end_layout
\begin_layout Enumerate
offset can be used to start the array data at some offset in the buffer.
\end_layout
\end_deeper
\begin_layout Note
The ndarray uses the default no-op __init__
\begin_inset LatexCommand index
name "ndarray!special methods!init"
\end_inset
function because the array is completely initialized after __new__ is called.
\end_layout
\begin_layout Description
__array__
\begin_inset LatexCommand index
name "ndarray!special methods!array"
\end_inset
(dtype {None})
\end_layout
\begin_layout Description
\InsetSpace ~
This is a special method that should always return an object of type ndarray.
Useful for subclasses that need to get to the ndarray object.
\end_layout
\begin_layout Description
__array_wrap__
\begin_inset LatexCommand index
name "ndarray!special methods!array\\_wrap"
\end_inset
(arr)
\end_layout
\begin_layout Description
\InsetSpace ~
This is a special method that always returns an object of the same Python
type as self using the array passed as an argument.
This is mainly useful for subclasses as it is an easy way to get the subclass
back from an ndarray.
\end_layout
\begin_layout Description
__lt__
\begin_inset LatexCommand index
name "ndarray!special methods!lt"
\end_inset
(other)
\end_layout
\begin_layout Description
__le__
\begin_inset LatexCommand index
name "ndarray!special methods!le"
\end_inset
(other)
\end_layout
\begin_layout Description
__gt__
\begin_inset LatexCommand index
name "ndarray!special methods!gt"
\end_inset
(other)
\end_layout
\begin_layout Description
__ge__
\begin_inset LatexCommand index
name "ndarray!special methods!ge"
\end_inset
(other)
\end_layout
\begin_layout Description
__eq__
\begin_inset LatexCommand index
name "ndarray!special methods!eq"
\end_inset
(other)
\end_layout
\begin_layout Description
__ne__
\begin_inset LatexCommand index
name "ndarray!special methods!ne"
\end_inset
(other)
\end_layout
\begin_layout Description
\InsetSpace ~
Defined to support rich comparisons (<, <=, >, >=, ==, !=) on ndarrays
using universal functions.
\end_layout
\begin_layout Description
__str__
\begin_inset LatexCommand index
name "ndarray!special methods!str"
\end_inset
()
\end_layout
\begin_layout Description
__repr__
\begin_inset LatexCommand index
name "ndarray!special methods!repr"
\end_inset
()
\end_layout
\begin_layout Description
\InsetSpace ~
These functions print the array when called by str(self) and repr(self)
respectively.
Array printing can be changed using set_string_function(..).
Default array printing has been borrowed from numarray whose printing code
was written by Perry Greenfield and J.
Todd Miller.
By default, arrays print such that
\end_layout
\begin_layout Enumerate
The last axis is always printed left to right.
\end_layout
\begin_layout Enumerate
The next-to-last axis is printed top to bottom.
\end_layout
\begin_layout Enumerate
Remaining axes are printed top to bottom with increasing numbers of separators.
\end_layout
\begin_layout Description
\InsetSpace ~
Five parameters of the printing can be set using keyword arguments with
\family typewriter
set_printoptions(...)
\family default
.
The parameters
\begin_inset LatexCommand index
name "set\\_printoptions"
\end_inset
can all be retrieved using
\family typewriter
get_printoptions()
\family default
.
These printing options
\begin_inset LatexCommand index
name "get\\_printoptions"
\end_inset
are
\end_layout
\begin_deeper
\begin_layout Description
precision the number of digits of precision for floating point output (default
8);
\end_layout
\begin_layout Description
threshold total number of array elements which triggers summarization rather
than full representation (default 1000);
\end_layout
\begin_layout Description
edgeitems number of array items in summary at beginning an end of each dimension
(default 3);
\end_layout
\begin_layout Description
linewidth the number of characters per line for the purpose of inserting
line breaks (default 71);
\end_layout
\begin_layout Description
suppress Boolean indicating whether or not to suppress printing of small
floating point values using scientific notation (default False).
\end_layout
\end_deeper
\begin_layout Description
__nonzero__
\begin_inset LatexCommand index
name "ndarray!special methods!nonzero"
\end_inset
()
\end_layout
\begin_layout Description
\InsetSpace ~
Truth-value testing for the array as a whole.
It is called whenever the truth value of the ndarray as a whole object
is required.
This raises an error if the number of elements in the the array is larger
than 1 because the truth value of such arrays is ambiguous.
Use .any() and .all() instead to be clear about what is meant in such cases.
If the number of elements is 0 then False is returned.
If there is one element in the array, then the truth-value of this element
is returned.
\end_layout
\begin_layout Subsection
Container customization
\end_layout
\begin_layout Description
__len__
\begin_inset LatexCommand index
name "ndarray!special methods!len"
\end_inset
()
\end_layout
\begin_layout Description
\InsetSpace ~
Returns self.shape[0].
It is called in response to len(self).
Use self.size to get the total number of elements in the array.
\end_layout
\begin_layout Description
\InsetSpace ~
Notice that the default Python iterator for sequences is used when arrays
are used in places that expect an iterator.
This iterator returns successively self[0], self[1], ..., self[self.__len__()].
Use self.flat to get an iterator that walks through the entire array one
element at a time.
\end_layout
\begin_layout Description
__getitem__
\begin_inset LatexCommand index
name "ndarray!special methods!getitem"
\end_inset
(key)
\end_layout
\begin_layout Description
\InsetSpace ~
Called when evaluating self[key] construct.
Items from the array can be selected using this customization.
This construct has both standard and extended indexing abilities which
are explained in Section
\begin_inset LatexCommand ref
reference "sec:Array-indexing"
\end_inset
.
A named field can be retrieved if key is a string and fields are defined
in the dtypedescr object associated with this array.
\end_layout
\begin_layout Description
__setitem__
\begin_inset LatexCommand index
name "ndarray!special methods!setitem"
\end_inset
(key, value)
\end_layout
\begin_layout Description
\InsetSpace ~
Called when evaluating self[key]=value.
Items in the array can be set using this construct.
This construct is explained in Section
\begin_inset LatexCommand ref
reference "sec:Array-indexing"
\end_inset
.
A named field can be set if key is a string and fields are defined in the
dtypedescr object associated with this array.
\end_layout
\begin_layout Description
__getslice__
\begin_inset LatexCommand index
name "ndarray!special methods!getslice"
\end_inset
(i, j)
\end_layout
\begin_layout Description
\InsetSpace ~
Equivalent to self.__getitem__(slice(i,j)) but defined mainly so that C
code can use the sequence interface.
Called to evaluate self[i:j]
\end_layout
\begin_layout Description
__setslice__
\begin_inset LatexCommand index
name "ndarray!special methods!setslice"
\end_inset
(i, j, value)
\end_layout
\begin_layout Description
\InsetSpace ~
Equivalent to self.__setitem__(slice(i,j), value) but defined mainly so
C code can use the sequence interface.
Called to evaluate self[i:j] = value.
\end_layout
\begin_layout Description
__contains__
\begin_inset LatexCommand index
name "ndarray!special methods!contains"
\end_inset
(item)
\end_layout
\begin_layout Description
\InsetSpace ~
Called to determine truth value of the
\family typewriter
item in self
\family default
construct.
Returns the equivalent of (self==item).any()
\end_layout
\begin_layout Subsection
Arithmetic customization
\end_layout
\begin_layout Subsubsection
Binary
\end_layout
\begin_layout Description
__add__
\begin_inset LatexCommand index
name "ndarray!special methods!add"
\end_inset
(other)
\end_layout
\begin_layout Description
__sub__
\begin_inset LatexCommand index
name "ndarray!special methods!sub"
\end_inset
(other)
\end_layout
\begin_layout Description
__mul__
\begin_inset LatexCommand index
name "ndarray!special methods!mul"
\end_inset
(self, other)
\end_layout
\begin_layout Description
__div__
\begin_inset LatexCommand index
name "ndarray!special methods!div"
\end_inset
(other)
\end_layout
\begin_layout Description
__truediv__
\begin_inset LatexCommand index
name "ndarray!special methods!truediv"
\end_inset
(other)
\end_layout
\begin_layout Description
__floordiv__
\begin_inset LatexCommand index
name "ndarray!special methods!floordiv"
\end_inset
(other)
\end_layout
\begin_layout Description
__mod__
\begin_inset LatexCommand index
name "ndarray!special methods!mod"
\end_inset
(other)
\end_layout
\begin_layout Description
__divmod__
\begin_inset LatexCommand index
name "ndarray!special methods!divmod"
\end_inset
(other)
\end_layout
\begin_layout Description
__pow__
\begin_inset LatexCommand index
name "ndarray!special methods!pow"
\end_inset
(other[,modulo])
\end_layout
\begin_layout Description
__lshift__
\begin_inset LatexCommand index
name "ndarray!special methods!lshift"
\end_inset
(other)
\end_layout
\begin_layout Description
__rshift__
\begin_inset LatexCommand index
name "ndarray!special methods!rshift"
\end_inset
(other)
\end_layout
\begin_layout Description
__and__
\begin_inset LatexCommand index
name "ndarray!special methods!and"
\end_inset
(other)
\end_layout
\begin_layout Description
__or__
\begin_inset LatexCommand index
name "ndarray!special methods!or"
\end_inset
(other)
\end_layout
\begin_layout Description
__xor__
\begin_inset LatexCommand index
name "ndarray!special methods!xor"
\end_inset
(other)
\end_layout
\begin_layout Description
\InsetSpace ~
These methods are defined for ndarrays to implement the operations (
\family typewriter
+
\family default
,
\family typewriter
-
\family default
,
\family typewriter
*
\family default
,
\family typewriter
/,
\family default
\family typewriter
/,
\family default
\family typewriter
//
\family default
,
\family typewriter
%
\family default
,
\family typewriter
divmod()
\family default
,
\family typewriter
**
\family default
or
\family typewriter
pow()
\family default
,
\family typewriter
<<,
\family default
\family typewriter
>>
\family default
,
\family typewriter
&
\family default
,
\family typewriter
^
\family default
,
\family typewriter
|
\family default
).
This is done using calls to the corresponding universal function object
(add, subtract, multiply, divide, true_divide, floor_divide, remainder,
divide and remainder, power, left_shift, right_shift, bitwise_and, bitwise_xor,
bitwise_or).
These implement element-by-element operations for arrays that are broadcastable
to the same shape.
\end_layout
\begin_layout Itemize
any third argument to
\family typewriter
pow()
\family default
is silently ignored as the underlying ufunc (power) only takes two arguments.
\end_layout
\begin_layout Itemize
the three division operators are all defined, div is active by default,
truediv is active when __future__.division is in effect.
\end_layout
\begin_layout Note
Because it is a built-in type (written in C), the __r__ special methods
are not directly defined for the ndarray.
\end_layout
\begin_layout Subsubsection
In-place
\end_layout
\begin_layout Description
__iadd__
\begin_inset LatexCommand index
name "ndarray!special methods!iadd"
\end_inset
(other)
\end_layout
\begin_layout Description
__isub__
\begin_inset LatexCommand index
name "ndarray!special methods!isub"
\end_inset
(other)
\end_layout
\begin_layout Description
__imul__
\begin_inset LatexCommand index
name "ndarray!special methods!imul"
\end_inset
(other)
\end_layout
\begin_layout Description
__idiv__
\begin_inset LatexCommand index
name "ndarray!special methods!idiv"
\end_inset
(other)
\end_layout
\begin_layout Description
__itruediv__
\begin_inset LatexCommand index
name "ndarray!special methods!itruediv"
\end_inset
(other)
\end_layout
\begin_layout Description
__ifloordiv__
\begin_inset LatexCommand index
name "ndarray!special methods!ifloordiv"
\end_inset
(other)
\end_layout
\begin_layout Description
__imod__
\begin_inset LatexCommand index
name "ndarray!special methods!imod"
\end_inset
(other)
\end_layout
\begin_layout Description
__ipow__
\begin_inset LatexCommand index
name "ndarray!special methods!ipow"
\end_inset
(other)
\end_layout
\begin_layout Description
__ilshift__
\begin_inset LatexCommand index
name "ndarray!special methods!ilshift"
\end_inset
(other)
\end_layout
\begin_layout Description
__irshift__
\begin_inset LatexCommand index
name "ndarray!special methods!irshift"
\end_inset
(other)
\end_layout
\begin_layout Description
__iand__
\begin_inset LatexCommand index
name "ndarray!special methods!iand"
\end_inset
(other)
\end_layout
\begin_layout Description
__ixor__
\begin_inset LatexCommand index
name "ndarray!special methods!ixor"
\end_inset
(other)
\end_layout
\begin_layout Description
__ior__
\begin_inset LatexCommand index
name "ndarray!special methods!ior"
\end_inset
(other)
\end_layout
\begin_layout Description
\InsetSpace ~
These methods are implemented to handle the inplace operatiors (
\family typewriter
+=
\family default
,
\family typewriter
-=
\family default
,
\family typewriter
*=
\family default
,
\family typewriter
/=
\family default
,
\family typewriter
/=
\family default
,
\family typewriter
//=
\family default
,
\family typewriter
%=
\family default
,
\family typewriter
**
\family default
=,
\family typewriter
<<
\family default
=,
\family typewriter
>>=
\family default
,
\family typewriter
&=
\family default
,
\family typewriter
^=
\family default
,
\family typewriter
|=
\family default
).
The inplace operators are implemented using the corresponding ufunc and
its ability to take an output argument (which is set as self).
Using inplace operations can save space and time and is therefore encouraged
whenever appropriate.
\end_layout
\begin_layout Warning
In place operations will perform the calculation using the precision decided
by the data type of the two operands, but will silently downcast the result
(if necessary) so it can fit back into the array.
Therefore, for mixed precision calculations, a = B can be different
than a = a B.
For example, suppose a=ones((3,3)).
Then a+=3j is different than a=a+3j While they both perform the same computatio
n, a+=3j casts the result to fit back in a, while a=a+3j re-binds the name
a to the result.
\end_layout
\begin_layout Subsubsection
Unary operations
\end_layout
\begin_layout Description
__neg__
\begin_inset LatexCommand index
name "ndarray!special methods!neg"
\end_inset
(self)
\end_layout
\begin_layout Description
__pos__
\begin_inset LatexCommand index
name "ndarray!special methods!pos"
\end_inset
(self)
\end_layout
\begin_layout Description
__abs__
\begin_inset LatexCommand index
name "ndarray!special methods!abs"
\end_inset
(self)
\end_layout
\begin_layout Description
__invert__
\begin_inset LatexCommand index
name "ndarray!special methods!invert"
\end_inset
(self)
\end_layout
\begin_layout Description
\InsetSpace ~
These functions are called in response to the unary operations (
\family typewriter
-
\family default
,
\family typewriter
+
\family default
,
\family typewriter
abs()
\family default
,
\family typewriter
~
\family default
).
With the exception of __pos__, these are implemented using ufuncs (negative,
absolute, invert).
The unary
\family typewriter
+
\family default
operator, however simply calls self.copy(), and can therefore be used to
get a copy of an array.
\end_layout
\begin_layout Description
__complex__
\begin_inset LatexCommand index
name "ndarray!special methods!complex"
\end_inset
(self)
\end_layout
\begin_layout Description
__int__
\begin_inset LatexCommand index
name "ndarray!special methods!int"
\end_inset
(self)
\end_layout
\begin_layout Description
__long__
\begin_inset LatexCommand index
name "ndarray!special methods!long"
\end_inset
(self)
\end_layout
\begin_layout Description
__float__
\begin_inset LatexCommand index
name "ndarray!special methods!float"
\end_inset
(self)
\end_layout
\begin_layout Description
__oct__
\begin_inset LatexCommand index
name "ndarray!special methods!oct"
\end_inset
(self)
\end_layout
\begin_layout Description
__hex__
\begin_inset LatexCommand index
name "ndarray!special methods!hex"
\end_inset
(self)
\end_layout
\begin_layout Description
\InsetSpace ~
These functions are also defined for the
\family typewriter
ndarray
\family default
object to handle the operations
\family typewriter
complex()
\family default
,
\family typewriter
int()
\family default
,
\family typewriter
long()
\family default
,
\family typewriter
float()
\family default
,
\family typewriter
oct()
\family default
, and
\family typewriter
hex()
\family default
.
They work only on arrays that have one element in them and return the appropria
te scalar
\begin_inset LatexCommand index
name "ndarray!special methods|)"
\end_inset
.
\end_layout
\begin_layout Tip
The function called to implement many arithmetic special methods for arrays
can be modified using the function set_numeric_ops.
This function is called with keyword arguments indicating which operation(s)
to replace.
A dictionary is returned containing showing the old functions.
By default, these functions are set to the corresponding ufunc.
\end_layout
\begin_layout Section
Array indexing
\end_layout
\begin_layout Standard
\begin_inset LatexCommand label
name "sec:Array-indexing"
\end_inset
\end_layout
\begin_layout Standard
More powerful array
\begin_inset LatexCommand index
name "indexing|("
\end_inset
indexing
\begin_inset LatexCommand index
name "ndarray!special methods!getitem"
\end_inset
was an important extension introduced by numarray, and was therefore an
important part of the development of NumPy.
In particular, the desire to select arbitrary elements based on their position
in the array, and according to a mask was desirable.
\end_layout
\begin_layout Standard
There are two kinds of indexing available using the
\family typewriter
X[obj]
\family default
syntax: basic slicing, and advanced indexing
\begin_inset LatexCommand index
name "ndarray!special methods!setitem"
\end_inset
.
For the description of this syntax given below, X is the array to-be-sliced
and obj is the
\emph on
selection
\emph default
object.
Furthermore, define
\begin_inset Formula $N\equiv$
\end_inset
X.ndim.
These two methods of slicing have different behavior and are triggered
depending on obj.
Adding additional functionality yet remaining compatible with old uses
of slicing complicated the rules a little.
Hopefully, after studying this section, you will have a firm grasp of what
kind of selection will be initiated depending on the selection object.
\end_layout
\begin_layout Tip
in Python X[(exp1, exp2, ..., expN)] is equivalent to X[exp1, exp2, ..., expN]
as the latter is just syntactic sugar for the former.
\end_layout
\begin_layout Subsection
Basic Slicing
\end_layout
\begin_layout Standard
Basic slicing
\begin_inset LatexCommand index
name "ndarray!special methods!getslice"
\end_inset
extends Python's basic concept of slicing
\begin_inset LatexCommand index
name "ndarray!special methods!setslice"
\end_inset
to N dimensions.
Basic slicing occurs when obj is a slice object (constructed by start:stop:step
notation inside of brackets), an integer, or a tuple of slice objects and
integers.
Ellipsis and newaxis objects can be interspersed with these as well.
In order to remain backward compatible with a common usage in Numeric,
basic slicing is also initiated if the selection object is any sequence
(such as a list) containing slice objects, the ellipsis
\begin_inset LatexCommand index
name "ellipsis"
\end_inset
object, or the newaxis
\begin_inset LatexCommand index
name "newaxis"
\end_inset
object, but no integer arrays or other embedded sequences.
\end_layout
\begin_layout Standard
The standard rules of sequence slicing apply to basic slicing on a per-dimension
basis (including using a step index).
Some useful concepts to remember include:
\end_layout
\begin_layout Itemize
The basic slice syntax is '
\begin_inset Formula $i:j:k$
\end_inset
' where
\begin_inset Formula $i$
\end_inset
is the starting index,
\begin_inset Formula $j$
\end_inset
is the stopping index, and
\begin_inset Formula $k$
\end_inset
is the step (
\begin_inset Formula $k\neq0$
\end_inset
).
This selects the
\begin_inset Formula $m$
\end_inset
elements (in the corresponding dimension) with index values
\begin_inset Formula $i,\, i+k,\,\ldots,\, i+(m-1)k$
\end_inset
where
\begin_inset Formula $m=q+(r\neq0)$
\end_inset
where
\begin_inset Formula $q$
\end_inset
and
\begin_inset Formula $r$
\end_inset
are the quotient and remainder obtained by dividing
\begin_inset Formula $j-i$
\end_inset
by
\begin_inset Formula $k$
\end_inset
:
\begin_inset Formula $j-i=qk+r$
\end_inset
, so that
\begin_inset Formula $i+\left(m-1\right)k0$
\end_inset
and
\begin_inset Formula $n$
\end_inset
for
\begin_inset Formula $k<0$
\end_inset
.
If
\begin_inset Formula $j$
\end_inset
is not given it defaults to
\begin_inset Formula $n$
\end_inset
for
\begin_inset Formula $k>0$
\end_inset
and
\begin_inset Formula $-1$
\end_inset
for
\begin_inset Formula $k<0$
\end_inset
.
If
\begin_inset Formula $k$
\end_inset
is not given it defaults to 1.
Note that '::' is the same as ':' and means select all indices along this
axis.
\end_layout
\begin_layout Itemize
If the number of objects in the selection tuple is less than
\begin_inset Formula $N$
\end_inset
, then ':' is assumed for any remaining dimensions.
\end_layout
\begin_layout Itemize
Ellipsis expand to the number of ':' objects needed to make a selection
tuple of the same length as X.ndim.
Only one ellipsis is expanded, any others are interpreted as more ':'
\end_layout
\begin_layout Itemize
Each newaxis object in the selection tuple serves to expand the dimensions
of the resulting selection by one unit-length dimension.
The added dimension is the position of the newaxis object in the selection
tuple.
\end_layout
\begin_layout Itemize
An integer,
\begin_inset Formula $i$
\end_inset
, returns the same values as
\begin_inset Formula $i:i+1$
\end_inset
\series bold
except
\series default
the dimensionality of the returned object is reduced by 1.
In particular, a selection tuple with the
\begin_inset Formula $p^{\textrm{th}}$
\end_inset
element an integer (and all other entries ':') returns the corresponding
sub-array with dimension
\begin_inset Formula $N-1$
\end_inset
.
If
\begin_inset Formula $N=1,$
\end_inset
then the returned object is an Array Scalar.
These objects are explained in Chapter
\begin_inset LatexCommand ref
reference "cha:Scalar-objects"
\end_inset
.
\end_layout
\begin_layout Itemize
If the selection tuple has all entries ':' except the
\begin_inset Formula $p^{\textrm{th}}$
\end_inset
entry which is a slice object
\begin_inset Formula $i:j:k$
\end_inset
, then the returned array has dimension
\begin_inset Formula $N$
\end_inset
formed by concatenating the sub-arrays returned by integer indexing of
elements
\begin_inset Formula $i$
\end_inset
,
\begin_inset Formula $i+k$
\end_inset
,
\begin_inset Formula $i+(m-1)k0$
\end_inset
(or we wouldn't be doing advanced integer indexing).
\end_layout
\begin_layout Itemize
If
\begin_inset Formula $N_{s}=0$
\end_inset
then the
\begin_inset Formula $M$
\end_inset
-dimensional result is constructed by varying the index tuple
\begin_inset Formula $\left(i_{1},\ldots,i_{M}\right)$
\end_inset
over the range of the result shape and for each value of the index tuple
setting:
\begin_inset Formula \[
\textrm{result[$i_{1},\ldots,i_{M}$]=X[ind$_{1}$[$i_{1},\ldots i_{M}$], ind$_{2}$[$i_{1},\ldots,i_{M}$], \, etc.,\, ind$_{N}$[$i_{1},\ldots,i_{M}$]}.\]
\end_inset
\end_layout
\begin_deeper
\begin_layout Description
Example: Suppose the shape of the broadcasted indexing arrays is 3-dimensional
and
\begin_inset Formula $N$
\end_inset
is 2.
Then the result is found by letting
\begin_inset Formula $i,j,k$
\end_inset
run over the shape found by broadcasting
\begin_inset Formula $\textrm{ind}_{1},$
\end_inset
and
\begin_inset Formula $\textrm{ind}_{2},$
\end_inset
and for each
\begin_inset Formula $i,j,k$
\end_inset
setting result[
\begin_inset Formula $i,j,k$
\end_inset
] = X[
\begin_inset Formula $\textrm{ind}_{1}[i,j,k]$
\end_inset
,
\begin_inset Formula $\textrm{ind}_{2}[i,j,k]$
\end_inset
].
\end_layout
\end_deeper
\begin_layout Itemize
If
\begin_inset Formula $N_{s}>0$
\end_inset
, then partial indexing is done.
This can be somewhat mind-boggling to understand, but if you think in terms
of the shapes of the arrays involved, it can be easier to grasp what happens.
In simple cases (
\emph on
i.e.
\emph default
one indexing array and
\begin_inset Formula $N-1$
\end_inset
slice objects) it does exactly what you would expect (concatenation of
repeated application of basic slicing).
The rule for partial indexing is that the shape of the result (or the interpret
ed shape of the object to be used in setting) is the shape of X with the
indexed subspace replaced with the broadcasted indexing subspace.
If the index subspaces are right next to each other, then the broadcasted
indexing space directly replaces all of the indexed subspaces in X.
If the indexing subspaces are separated (by slice objects), then the broadcaste
d indexing space is first, followed by the sliced subspace of X.
\end_layout
\begin_deeper
\begin_layout Description
Example\InsetSpace ~
1: Suppose X.shape is (10,20,30) and ind is a (2,3,4) indexing intp
array, then result=X[...,ind,:] has shape (10,2,3,4,30) because the (20,)-shaped
subspace has been replaced with a (2,3,4)-shaped broadcasted indexing subspace.
If we let
\begin_inset Formula $i,j,k$
\end_inset
loop over the (2,3,4)-shaped subspace then result[...,i,j,k,:] = X[...,ind[i,j,k],:].
This example produces the same result as X.take(ind,axis=-2).
\end_layout
\begin_layout Description
Example\InsetSpace ~
2: Now let X.shape be (10,20,30,40,50) and suppose
\begin_inset Formula $\textrm{ind}_{1}$
\end_inset
and
\begin_inset Formula $\textrm{ind}_{2}$
\end_inset
are broadcastable to the shape (2,3,4).
Then X[:,ind
\begin_inset Formula $_{1}$
\end_inset
,ind
\begin_inset Formula $_{2}$
\end_inset
] has shape (10,2,3,4,40,50) because the (20,30)-shaped subspace from X
has been replaced with the (2,3,4) subspace from the indices.
However, X[:,ind
\begin_inset Formula $_{1}$
\end_inset
,:,ind
\begin_inset Formula $_{2}$
\end_inset
,:] has shape (2,3,4,10,30,50) because there is no unambiguous place to
drop in the indexing subspace, thus it is tacked-on to the beginning.
It is always possible to use .transpose() to move the sups pace anywhere
desired.
This example cannot be replicated using take.
\end_layout
\end_deeper
\begin_layout Subsubsection
Boolean
\end_layout
\begin_layout Standard
This advanced selection occurs when obj is an array object of Boolean type
(such as may be returned from comparison operators).
It is always equivalent to (but faster than) X[obj.nonzero()] where as described
above obj.nonzero() returns a tuple (of length obj.ndim) of integer index
arrays showing the True elements of obj.
\end_layout
\begin_layout Standard
The special case when obj.ndim == X.ndim is worth mentioning.
In this case X[obj] returns a 1-dimensional array filled with the elements
of X corresponding to the True values of obj.
It The search order will be C-style (last index varies the fastest).
If obj has True values at entries that are outside of the bounds of X,
then an index error will be raised.
\end_layout
\begin_layout Standard
You can also use Boolean arrays as element of the selection tuple.
In such instances, they will always be interpreted as nonzero(obj) and
the equivalent integer indexing will be done.
In general you can think of indexing with Boolean arrays as indexing with
nonzero().
\end_layout
\begin_layout Warning
the definition of advanced selection means that X[(1,2,3),] is fundamentally
different than X[(1,2,3)].
The latter is equivalent to X[1,2,3] which will trigger basic selection
while the former will trigger advanced selection.
Be sure to understand why this is True.
You should also recognize that x[[1,2,3]] will trigger advanced selection,
but X[[1,2,slice(None)]] will trigger basic selection.
\end_layout
\begin_layout Subsection
Flat Iterator indexing
\end_layout
\begin_layout Standard
As mentioned previously, X.flat returns an iterator that will iterate over
the entire array (in C-contiguous style with the last index varying the
fastest).
This iterator object can also be indexed using basic slicing or advanced
indexing as long as the selection object is not a tuple.
This should be clear from the fact that X.flat is a 1-dimensional view.
X.flat can be used for integer indexing using 1-dimensional C-style-flat
indices.
The shape of any returned array is therefore the shape of the integer indexing
\begin_inset LatexCommand index
name "indexing|)"
\end_inset
object
\begin_inset LatexCommand index
name "ndarray|)"
\end_inset
.
\end_layout
\begin_layout Chapter
Basic Routines
\end_layout
\begin_layout Quotation
Do not pray for tasks equal to your powers; pray for powers equal to your
tasks.
Then the doing of your work shall be no miracle, but you shall be the miracle.
\end_layout
\begin_layout Right Address
---
\emph on
Phillips Brooks
\end_layout
\begin_layout Quote
Education isn't how much you have committed to memory, or even how much
you know.
It's being able to differentiate between what you do know and what you
don't.
\end_layout
\begin_layout Right Address
---
\emph on
Anatole France
\end_layout
\begin_layout Section
Creating arrays
\end_layout
\begin_layout Description
array
\begin_inset LatexCommand index
name "array"
\end_inset
(object=, dtype=None, copy=True, order=None, subok=False, ndmin=0)
\end_layout
\begin_layout Description
\InsetSpace ~
Create a new ndarray of data type, dtype (or determined from object if
dtype is None).
The shape of the new array will be determined from object.
If copy is True, then ensure a copy of the object is made.
If copy is False, then the returned object is a copy of the array only
if dtype is not equivalent to the data type of object.
If order is 'Fortran' then the resulting array will be in Fortran order,
otherwise it is in C order.
If subok (subclasses are O.K.) is True then pass through subclasses of the
array object if possible.
If subok is False then only ndarray objects may be returned.
The ndmin parameter specifies that the returned array must have at least
the given number of dimensions.
\end_layout
\begin_layout Description
asarray
\begin_inset LatexCommand index
name "asarray"
\end_inset
(object=, dtype=None, order=None)
\end_layout
\begin_layout Description
\InsetSpace ~
Exactly the same as array(...) except the default copy argument is False,
and subok is always False.
Using this function always returns the base class ndarray.
\end_layout
\begin_layout Description
asanyarray
\begin_inset LatexCommand index
name "asanyarray"
\end_inset
(object, dtype=None, order=None)
\end_layout
\begin_layout Description
\InsetSpace ~
Thin wrapper around array(...) with subok=1.
You should use this routine if you are only making use of the array attributes,
and believe the calculations that will follow would work with any subclass
of the array.
Use of this routine increases the chance that array subclasses will interact
seamlessly with your function --- returning the same subclasses.
\end_layout
\begin_layout Description
require
\begin_inset LatexCommand index
name "require"
\end_inset
(object, dtype=None, requirements=None)
\end_layout
\begin_layout Description
\InsetSpace ~
Require a Python object to be an ndarray (or a sub-class) of the given
data-type if it can be cast safely, otherwise raise an error.
The requirements, if given, are a sequence containing the requested combination
of the flags 'C_CONTIGUOUS' ('C'), 'F_CONTIGUOUS' ('F'), 'ALIGNED' ('A'),
'WRITEABLE' ('W'), 'OWNDATA' ('O'), and the special directive 'ENSUREARRAY'
('E').
These strings dictate which flags should be set on the return array (note
only one of 'F_CONTIGUOUS' or 'C_CONTIGUOUS' should be used and 'F_CONTIGUOUS'
over-rides 'C_CONTIGUOUS').
The special directive 'ENSUREARRAY' makes sure that a base-class ndarray
is returned instead of allowing sub-classes to pass through.
This function is particularly useful in a Python interface to C-code (say
called using ctypes
\begin_inset LatexCommand index
name "ctypes"
\end_inset
).
\end_layout
\begin_layout Description
arange
\begin_inset LatexCommand index
name "arange"
\end_inset
(start=, stop=None, step=1, dtype=None)
\end_layout
\begin_layout Description
\InsetSpace ~
Function similar to Python's built-in range() function except it returns
an ndarray object.
Return a 1-d array of data type, dtype (or determined from the start, stop,
and step objects if None), that starts at start, ends
\emph on
before
\emph default
stop and is incremented by step.
The returned array has length
\begin_inset Formula $n$
\end_inset
where
\begin_inset Formula \[
n=\left\lceil \frac{\textrm{stop}-\textrm{start}}{\textrm{step}}\right\rceil \]
\end_inset
with element
\begin_inset Formula $i$
\end_inset
equal to
\begin_inset Formula $\textrm{start}+i\cdot\textrm{step}.$
\end_inset
If stop is None, then the first argument is interpreted as stop and start
is 0.
\end_layout
\begin_layout Note
By definition of the ceiling function (denoted by
\begin_inset Formula $\left\lceil x\right\rceil $
\end_inset
), we know that
\begin_inset Formula $x\leq\left\lceil x\right\rceil >> indices((2,3))
\newline
array([[[0, 0, 0],
\newline
[1, 1, 1]],
\newline
\newline
[[0, 1, 2],
\newline
[0, 1, 2]]])
\end_layout
\begin_layout Description
fromfunction
\begin_inset LatexCommand index
name "fromfunction"
\end_inset
(function, dimensions, **kwargs)
\end_layout
\begin_layout Description
\InsetSpace ~
Construct an array from a function called on a tuple of index grids.
The function should be able to take array arguments and process them like
ufuncs (use vectorize if it doesn't).
The function should accept as many arguments as there are dimensions which
is a sequence of numbers indicating the length of the desired output for
each axis.
Keyword arguments to function may also be passed in as keywords to fromfunction.
\end_layout
\begin_layout MyCode
>>> print fromfunction(lambda i,j: i+j, (2,3))
\newline
[[ 0.
1.
2.]
\newline
[ 1.
2.
3.]]
\end_layout
\begin_layout Description
identity
\begin_inset LatexCommand index
name "identity"
\end_inset
(n, dtype=intp)
\end_layout
\begin_layout Description
\InsetSpace ~
Return a 2-d array of shape (n,n) and data type, dtype with ones along
the main diagonal.
\end_layout
\begin_layout Description
where
\begin_inset LatexCommand index
name "where"
\end_inset
(condition[, x, y])
\end_layout
\begin_layout Description
\InsetSpace ~
Returns an array shaped like condition, that has the elements of x and
y respectively where condition is respectively true or false.
If x and y are not given, then it is equivalent to nonzero(condition).
\end_layout
\begin_layout Description
flatnonzero
\begin_inset LatexCommand index
name "flatnonzero"
\end_inset
(arr)
\end_layout
\begin_layout Description
\InsetSpace ~
Return indices that are non-zero in a flattened version of arr.
Equivalent to a.ravel().nonzero()[0].
\end_layout
\begin_layout Description
putmask
\begin_inset LatexCommand index
name "putmask"
\end_inset
(arr=, mask=, values=)
\end_layout
\begin_layout Description
\InsetSpace ~
Performs the equivalent of
\end_layout
\begin_layout LyX-Code
for n, obj in enumerate(
\series bold
mask
\series default
.flat):
\end_layout
\begin_layout LyX-Code
if obj:
\end_layout
\begin_layout LyX-Code
self.flat[n] =
\series bold
values
\series default
[n]
\end_layout
\begin_layout Description
\InsetSpace ~
The values array is repeated if it is too short.
In particular, this means that indexing on the values array is modular
it's length, which might be surprising you are expecting putmask to work
the same as arr[mask]=values.
\end_layout
\begin_layout Description
lexsort
\begin_inset LatexCommand index
name "lexsort"
\end_inset
(keys=, axis=-1)
\end_layout
\begin_layout Description
\InsetSpace ~
Return an array of indices similar to argsort except sorting is done using
all of the provided keys.
First a sort is computed using key[0], then the indices are further altered
by sorting on key[1].
This is repeated until sorting has been performed on all of the keys.
This is a useful function for multiple-field sorting.
\end_layout
\begin_layout MyCode
>>> a = [1,2,1,3,1,5]; b = [0,4,5,6,2,3]
\newline
>>> ind = lexsort((b,a))
\newline
>>> print
take(a,ind)
\newline
[1 1 1 2 3 5]
\newline
>>> print take(b,ind)
\newline
[0 2 5 4 6 3]
\end_layout
\begin_layout Description
\InsetSpace ~
Notice the order the keys had to be used in order to get a lexicographical
sorting order.
To clarify, suppose three equal-length sequences are fields of an underlying
data-type: (f1,f2,f3).
If we want to sort first on f1 and then on f2 and then on f3, the indices
that would accomplish that sort are obtained as lexsort((f3,f2,f1)).
\end_layout
\begin_layout Section
Operations on two or more arrays
\end_layout
\begin_layout Description
concatenate
\begin_inset LatexCommand index
name "concatenate"
\end_inset
(seq=, axis=0)
\end_layout
\begin_layout Description
\InsetSpace ~
Construct a new array from elements of the sequence object seq concatenated
along the given axis.
The elements of the sequence object must have compatible types and be the
same shape.
If axis is None, then flatten each element of seq before concatenating
together to construct a 1-d array.
\end_layout
\begin_layout Description
correlate
\begin_inset LatexCommand index
name "correlate"
\end_inset
(x, y, mode='valid')
\end_layout
\begin_layout Description
\InsetSpace ~
Compute the 1-d cross correlation of x and y keeping portions determined
by mode which may be 'valid' (0), 'same' (1), or 'full' (2).
The 'full' cross-correlation between two 1-d arrays is computed as
\begin_inset Formula \[
z\left[n\right]=\sum_{i=\max\left(n-M,0\right)}^{\min\left(n,K\right)}x\left[i\right]y\left[n+i\right],\]
\end_inset
for
\begin_inset Formula $n=0\ldots K+M$
\end_inset
where
\begin_inset Formula $K$
\end_inset
=len(
\begin_inset Formula $x$
\end_inset
)-1 and
\begin_inset Formula $M$
\end_inset
=len(
\begin_inset Formula $y$
\end_inset
)-1, and we assume
\begin_inset Formula $K\geq M$
\end_inset
(without loss of generality because we can interchange the roles of
\begin_inset Formula $x$
\end_inset
and
\begin_inset Formula $y$
\end_inset
without effect).
For this formula to work, we assume that
\begin_inset Formula $x[i]=0$
\end_inset
when
\begin_inset Formula $i\notin\left[0,K-1\right]$
\end_inset
and
\begin_inset Formula $y[j]=0$
\end_inset
when
\begin_inset Formula $j\neq[0,M-1]$
\end_inset
.
\end_layout
\begin_layout Description
\InsetSpace ~
If mode is 'same' then only the
\begin_inset Formula $K$
\end_inset
middle values are returned starting at
\begin_inset Formula $n=\left\lfloor \frac{M-1}{2}\right\rfloor $
\end_inset
.
If the flag has a value of 'valid' then only the middle
\begin_inset Formula $K-M+1=\left(K+1\right)-\left(M+1\right)+1$
\end_inset
output values are returned starting at
\begin_inset Formula $n=M.$
\end_inset
\end_layout
\begin_layout Description
convolve
\begin_inset LatexCommand index
name "convolve"
\end_inset
(x, y, mode='valid')
\end_layout
\begin_layout Description
\InsetSpace ~
Convolution is very similar to correlation except it is defined with one
sequence reversed:
\begin_inset Formula \[
z\left[n\right]=\sum_{i}x[i]y[n-i].\]
\end_inset
The mode keyword has the same effect as it does for correlation.
Convolution ('full') between two 1-d arrays implements polynomial multiplicatio
n where the array entries are viewed as coefficients for polynomials.
\end_layout
\begin_deeper
\begin_layout Description
Example: Consider that
\begin_inset Formula $(x^{3}+4x^{2}+2)$
\end_inset
\begin_inset Formula $\left(x^{4}+3x+1\right)$
\end_inset
=
\begin_inset Formula $x^{7}+4x^{6}+5x^{4}+13x^{3}+4x^{2}+6x+2.$
\end_inset
This can be determined by using the code
\family typewriter
convolve([1,4,0,2], [1,0,0,3,1])
\family default
which returns
\family typewriter
[1,4,0,5,13,4,6,2].
\family default
Notice the one-to-one alignment between the elements of the arrays and
the coefficients on powers of
\begin_inset Formula $x$
\end_inset
in the polynomial.
\end_layout
\end_deeper
\begin_layout Description
outer
\begin_inset LatexCommand index
name "outer"
\end_inset
(a, b)
\end_layout
\begin_layout Description
\InsetSpace ~
compute an outerproduct which is syntactic sugar for a.ravel() [:,newaxis]
* b.ravel() [newaxis,:] (after first converting a and b to ndarrays).
\end_layout
\begin_layout MyCode
>>> print outer([1,2,3],[10,100,1000])
\newline
[[ 10 100 1000]
\newline
[ 20 200 2000]
\newline
[ 30 300 3000]]
\end_layout
\begin_layout Description
inner
\begin_inset LatexCommand index
name "inner"
\end_inset
(a, b)
\end_layout
\begin_layout Description
\InsetSpace ~
Computes the inner product between two arrays.
This is an array that has shape a.shape[:-1] + b.shape[:-1] with elements
computed as the sum of the product of the elements from the last dimensions
of a and b.
In particular, let
\begin_inset Formula $I$
\end_inset
and
\begin_inset Formula $J$
\end_inset
be the super
\begin_inset Foot
status open
\begin_layout Standard
A super index is 0 or more integer indices used to index into an N-dimensional
array.
How many indices a super index represents should be implied by context.
\end_layout
\end_inset
indices selecting the 1-dimensional arrays
\begin_inset Formula $a[I,:]$
\end_inset
and
\begin_inset Formula $b[J,:]$
\end_inset
, then the resulting array,
\begin_inset Formula $r$
\end_inset
, is
\begin_inset Formula \[
r[I,J]=\sum_{k}a[I,k]b[J,k].\]
\end_inset
\end_layout
\begin_layout Description
dot
\begin_inset LatexCommand index
name "dot"
\end_inset
(a, b)
\end_layout
\begin_layout Description
\InsetSpace ~
Computes the dot (matrix) product between two arrays.
The product-sum is over the last dimension of
\begin_inset Formula $a$
\end_inset
and the second-to-last dimension of
\begin_inset Formula $b$
\end_inset
.
Specifically, if
\begin_inset Formula $I$
\end_inset
and
\begin_inset Formula $J$
\end_inset
are super indices for
\begin_inset Formula $a[I,:]$
\end_inset
and
\begin_inset Formula $b[J,:,j]$
\end_inset
so that
\begin_inset Formula $j$
\end_inset
is the index of the last dimension of
\begin_inset Formula $b$
\end_inset
.
Then, the shape of the resulting array is a.shape[:-1] + b.shape[:-2] + (b.shape[-
1],) with elements.
\begin_inset Formula \[
r[I,J,j]=\sum_{k}a[I,k]b[J,k,j],\]
\end_inset
\end_layout
\begin_layout Description
\begin_inset LatexCommand index
name "vdot"
\end_inset
vdot (a, b)
\end_layout
\begin_layout Description
\InsetSpace ~
Computes the dot product between two arrays (flattened into one-dimensional
vectors) after conjugating the first vector.
This is an inner-product following the physicists convention of conjugating
the first argument.
\begin_inset Formula \[
r=\sum_{k}\overline{\textrm{a.flat}[k]}\textrm{b.flat}[k].\]
\end_inset
\end_layout
\begin_layout Description
tensordot
\begin_inset LatexCommand index
name "tensordot"
\end_inset
(a, b, axes=(-1,0))
\end_layout
\begin_layout Description
\InsetSpace ~
Computes a dot-product between two arrays where the sum is taken over the
axes specified by the 2-sequence which can have either scalar or sequence
entries.
The axes specified are summed over and the remaining axes are used to construct
the result.
So, for example, if
\begin_inset Formula $a$
\end_inset
is
\begin_inset Formula $3\times4\times5$
\end_inset
and
\begin_inset Formula $b$
\end_inset
is
\begin_inset Formula $4\times3\times2$
\end_inset
then if axes=([1,0],[0,1]) (or axes=([0,1],[1,0])) the result will be
\begin_inset Formula $5\times2$
\end_inset
.
Let
\begin_inset Formula $I$
\end_inset
represent the indices of the un-summed axes in
\begin_inset Formula $a$
\end_inset
, let
\begin_inset Formula $J$
\end_inset
represent the indices of the un-summed axes in
\begin_inset Formula $b$
\end_inset
and let
\begin_inset Formula $K$
\end_inset
represent the the indices of the axes summed over in both
\begin_inset Formula $a$
\end_inset
and
\begin_inset Formula $b$
\end_inset
.
Also, let
\begin_inset Formula $a_{t}$
\end_inset
represent a transposed version of
\begin_inset Formula $a$
\end_inset
where the axes to be summed over are pushed to the end, and let
\begin_inset Formula $b_{t}$
\end_inset
represent a transposed version of
\begin_inset Formula $b$
\end_inset
where the axes to be summed over are pushed to the front.
Then, using
\begin_inset Formula $\sum_{K}$
\end_inset
to represent a multi-index sum, the result can be written as
\end_layout
\begin_layout Standard
\begin_inset Formula \[
r[I,J]=\sum_{K}a_{t}[I,K]b_{t}[K,J]\]
\end_inset
\end_layout
\begin_layout Description
cross
\begin_inset LatexCommand index
name "cross"
\end_inset
(a, b, axisa=-1, axisb=-1, axisc=-1, axis=None)
\end_layout
\begin_layout Description
\InsetSpace ~
Returns the cross product of two (arrays of) vectors.
The cross product is performed over the axes of the input arrays indicated
by the axisa, and axisb arguments.
For both arrays, the axis used must have dimension either 2 or 3.
If both axes used have dimension 2, then only the z-component of the equivalent
3-d cross product is returned.
Otherwise, the entire vector is returned.
The axisc argument gives the axis of the vectors in the returned cross-product
result.
If axis is not None, then it is assumed that axisa=axisb=axisc=axis (regardless
of what else is specified).
\end_layout
\begin_layout Description
allclose
\begin_inset LatexCommand index
name "allclose"
\end_inset
(a, b, rtol=
\begin_inset Formula $10^{-5}$
\end_inset
, atol=
\begin_inset Formula $10^{-8}$
\end_inset
)
\end_layout
\begin_layout Description
\InsetSpace ~
Returns true if all components of a and b are equal subject to the given
relative and absolute tolerances.
This returns true if every element of a and b satisfy
\begin_inset Formula \[
\left|a-b\right|<\textrm{atol}+\textrm{rtol}\left|b\right|.\]
\end_inset
\end_layout
\begin_layout Section
Printing arrays
\end_layout
\begin_layout Description
array2string
\begin_inset LatexCommand index
name "array2string"
\end_inset
(a)
\end_layout
\begin_layout Description
\InsetSpace ~
The default printing mechanism uses this function to produce a string from
an array.
\end_layout
\begin_layout Description
set_printoptions
\begin_inset LatexCommand index
name "set\\_printoptions"
\end_inset
(precision=None, theshold=None, edgeitems=None, linewidth=None, suppress=None)
\end_layout
\begin_layout Description
\InsetSpace ~
Set options associated with representing an array.
\end_layout
\begin_deeper
\begin_layout Description
precision the default number of digits of precision for floating point output
(default 8);
\end_layout
\begin_layout Description
threshold total number of array elements which triggers printing only the
\begin_inset Quotes eld
\end_inset
ends
\begin_inset Quotes erd
\end_inset
of the array rather than a full representation (default 1000);
\end_layout
\begin_layout Description
edgeitems number of array elements in summary at beginning and end of each
dimension (default 3);
\end_layout
\begin_layout Description
linewidth the number of characters per line (default 75);
\end_layout
\begin_layout Description
suppress Boolean value indicating whether or not to suppress printing of
small floating point values using scientific notation (default False).
\end_layout
\end_deeper
\begin_layout Description
get_printoptions
\begin_inset LatexCommand index
name "get\\_printoptions"
\end_inset
()
\end_layout
\begin_layout Description
\InsetSpace ~
Returns the values of precision, threshold, edgeitems, linewidth, and suppress
that control printing of arrays.
\end_layout
\begin_layout Description
set_string_function
\begin_inset LatexCommand index
name "set\\_string\\_function"
\end_inset
(func, repr=1)
\end_layout
\begin_layout Description
\InsetSpace ~
Set the function to use in response to str(array) or repr(array).
By default this function is array2string.
The function passed in must take an array argument and return a string.
If func is None, then the print function is reset to a simple internal
function.
\end_layout
\begin_layout Section
Functions redundant with methods
\end_layout
\begin_layout Standard
Several functions are available primarily for purposes of backward compatibility
with old Numeric, and are therefore redundant.
The functions are all simple wrappers for asarray(a).(*args, **kwds),
or are replaceable by attribute access.
The following list documents them.
It is not recommended that these functions be used in new programs, but
there are no plans for removing them as in functional form they work with
arbitrary sequences which is sometimes desirable.
The functions that mirror methods and attributes are:
\series bold
take
\series default
\begin_inset LatexCommand index
name "take"
\end_inset
,
\series bold
reshape
\series default
\begin_inset LatexCommand index
name "reshape"
\end_inset
,
\series bold
squeeze
\series default
\begin_inset LatexCommand index
name "squeeze"
\end_inset
,
\series bold
choose
\series default
\begin_inset LatexCommand index
name "choose"
\end_inset
,
\series bold
repeat
\series default
\begin_inset LatexCommand index
name "repeat"
\end_inset
,
\series bold
put
\series default
\begin_inset LatexCommand index
name "put"
\end_inset
,
\series bold
swapaxes
\series default
\begin_inset LatexCommand index
name "swapaxes"
\end_inset
,
\series bold
transpose
\series default
\begin_inset LatexCommand index
name "transpose"
\end_inset
,
\series bold
real
\series default
\begin_inset LatexCommand index
name "real"
\end_inset
,
\series bold
imag
\series default
\begin_inset LatexCommand index
name "imag"
\end_inset
,
\series bold
sort
\series default
\begin_inset LatexCommand index
name "sort"
\end_inset
,
\series bold
argsort
\series default
\begin_inset LatexCommand index
name "argsort"
\end_inset
,
\series bold
amax
\begin_inset LatexCommand index
name "amax"
\end_inset
, argmax
\series default
\begin_inset LatexCommand index
name "argmax"
\end_inset
,
\series bold
amin
\begin_inset LatexCommand index
name "amin"
\end_inset
\series default
,
\series bold
argmin
\series default
\begin_inset LatexCommand index
name "argmin"
\end_inset
,
\series bold
ptp
\series default
\begin_inset LatexCommand index
name "ptp"
\end_inset
,
\series bold
alen
\series default
\begin_inset LatexCommand index
name "alen"
\end_inset
,
\series bold
searchsorted
\series default
\begin_inset LatexCommand index
name "searchsorted"
\end_inset
,
\series bold
diagonal
\series default
\begin_inset LatexCommand index
name "diagonal"
\end_inset
,
\series bold
trace
\series default
\begin_inset LatexCommand index
name "trace"
\end_inset
,
\series bold
ravel
\series default
\begin_inset LatexCommand index
name "ravel"
\end_inset
,
\series bold
nonzero
\series default
\begin_inset LatexCommand index
name "nonzero"
\end_inset
,
\series bold
shape
\series default
\begin_inset LatexCommand index
name "shape"
\end_inset
,
\series bold
compress
\series default
\begin_inset LatexCommand index
name "compress"
\end_inset
,
\series bold
clip
\series default
\begin_inset LatexCommand index
name "clip"
\end_inset
,
\series bold
std
\series default
\begin_inset LatexCommand index
name "std"
\end_inset
,
\series bold
var
\series default
\begin_inset LatexCommand index
name "var"
\end_inset
,
\series bold
mean
\series default
\begin_inset LatexCommand index
name "mean"
\end_inset
,
\series bold
sum
\series default
\begin_inset LatexCommand index
name "sum"
\end_inset
,
\series bold
cumsum
\series default
\begin_inset LatexCommand index
name "cumsum"
\end_inset
,
\series bold
product
\series default
\begin_inset LatexCommand index
name "product"
\end_inset
,
\series bold
cumproduct
\series default
\begin_inset LatexCommand index
name "cumproduct"
\end_inset
,
\series bold
sometrue
\begin_inset LatexCommand index
name "sometrue"
\end_inset
\series default
(method is .any),
\series bold
alltrue
\begin_inset LatexCommand index
name "alltrue"
\end_inset
\series default
(method is .all),
\series bold
around
\begin_inset LatexCommand index
name "around"
\end_inset
\series default
(method is .round),
\series bold
rank
\begin_inset LatexCommand index
name "rank"
\end_inset
\series default
(attribute is .ndim),
\series bold
shape
\series default
\begin_inset LatexCommand index
name "shape"
\end_inset
,
\series bold
size
\begin_inset LatexCommand index
name "size"
\end_inset
\series default
(.size or .shape[axis]), and
\series bold
copy
\series default
\begin_inset LatexCommand index
name "copy"
\end_inset
.
\end_layout
\begin_layout Section
Dealing with data types
\end_layout
\begin_layout Description
dtype (obj, align=0)
\end_layout
\begin_layout Description
\InsetSpace ~
Return a data-type object from any object.
See Chapter
\begin_inset LatexCommand ref
reference "cha:Data-descriptor-objects"
\end_inset
for a more detailed explanation of what can be interpreted as a data-type
object and the meaning of the align keyword.
\end_layout
\begin_layout Description
maximum_sctype (arg)
\end_layout
\begin_layout Description
\InsetSpace ~
Returns the array-scalar type of highest precision of the same general
kind as arg which can be any recognized form for describing a data-type.
\end_layout
\begin_layout Description
issctype (obj)
\end_layout
\begin_layout Description
\InsetSpace ~
Returns True if obj is an array data type (or a recognized alias for one)
\end_layout
\begin_layout Description
obj2sctype (obj, default=None)
\end_layout
\begin_layout Description
\InsetSpace ~
Returns the array type object corresponding to obj which can be an array
type already, a python type object, an actual array, or any recognized
alias for an array type object.
If no suitable data type object can be determined, return default.
\end_layout
\begin_layout Description
sctype2char (sctype)
\end_layout
\begin_layout Description
\InsetSpace ~
Return the typecode character associated with an array-scalar type dtype.
The first argument is first converted to a dtype if it needs to be.
\end_layout
\begin_layout Tip
the type attribute of data-type objects are actual Python type objects subclasse
d in a hierarchy of types.
This can often be useful to check data types generically.
For example, issubclass(dtype.type, integer) can check to see if the data
type is one of the 10 different integer types.
The issubclass function, however, raises an error if either argument is
not an actual type object.
NumPy defines _(arg1, arg2) that will return false instead of raise an
error.
Alternatively, dtype.kind is a character describing the class of the data-type
so dtype.kind in 'iu' would also check to see if the data-type is an integer
type.
\end_layout
\begin_layout Description
can_cast (from=d1, to=d2)
\end_layout
\begin_layout Description
\InsetSpace ~
Return Boolean value indicating whether or not data type d1 can be cast
to data type d2 safely (without losing precision or information).
\end_layout
\begin_layout Chapter
Additional Convenience Routines
\end_layout
\begin_layout Quotation
A committee is twelve men doing the work of one.
\end_layout
\begin_layout Right Address
---
\emph on
John F.
Kennedy
\end_layout
\begin_layout Quotation
Your mind can only hold one thought at a time.
Make it a positive and constructive one.
\end_layout
\begin_layout Right Address
---
\emph on
H.
Jackson Brown Jr.
\end_layout
\begin_layout Section
Shape functions
\end_layout
\begin_layout Description
atleast_1d
\begin_inset LatexCommand index
name "atleast\\_1d"
\end_inset
(a1,a2,...,an)
\end_layout
\begin_layout Description
\InsetSpace ~
Force a sequence of arrays (including array scalars) to each be at least
1-d.
\end_layout
\begin_layout Description
atleast_2d
\begin_inset LatexCommand index
name "atleast\\_2d"
\end_inset
(a1,a2,...,an)
\end_layout
\begin_layout Description
\InsetSpace ~
Force a sequence of arrays (including array scalars) to each be at least
2-d.
Dimensions of length 1 are pre-pended to reach a two-dimensional array.
\end_layout
\begin_layout Description
atleast_3d
\begin_inset LatexCommand index
name "atleast\\_3d"
\end_inset
(a1,a2,...,an)
\end_layout
\begin_layout Description
\InsetSpace ~
Force a sequence of arrays (including array_scalars) to each be at least
3-d.
Dimensions of length 1 are pre-pended to reach a two-dimensional array.
\end_layout
\begin_layout Description
roll
\begin_inset LatexCommand index
name "roll"
\end_inset
(arr, shift, axis=None)
\end_layout
\begin_layout Description
\InsetSpace ~
Return a new array with the contents of arr shifted (rolled) by the amount
given in the integer argument shift along the axis specified.
If axis is None, then the shift takes place in the ravelled array (but
the returned array has the same shape as arr).
Elements that shift outside the array are rolled back into the array from
the opposite side.
\end_layout
\begin_layout Description
rollaxis
\begin_inset LatexCommand index
name "rollaxis"
\end_inset
(arr, axis, start)
\end_layout
\begin_layout Description
\InsetSpace ~
Return arr transposed so that the provided axis is inserted into the shape
before start with the other dimensions rolled.
Thus, if arr.shape is (i,j,k,l) then rollaxis(arr, 2, 0) has shape (k,i,j,l)
and rollaxis(arr, 1, 3) has shape (i,k,j,l).
\end_layout
\begin_layout Description
vstack
\begin_inset LatexCommand index
name "vstack"
\end_inset
(seq)
\end_layout
\begin_layout Description
\InsetSpace ~
Stack a sequence of arrays along the first axis (row wise).
Arrays in seq must have the same shape along all dimensions but the first.
Rebuilds array divided by vsplit.
All 1-d arrays will be stacked row-wise.
\end_layout
\begin_layout Description
hstack
\begin_inset LatexCommand index
name "hstack"
\end_inset
(seq)
\end_layout
\begin_layout Description
\InsetSpace ~
Stack a sequence of arrays along the second axis (column wise).
Arrays in seq must have the same shape along all dimensions but the second.
Rebuilds array divided by hsplit.
Notice that 1-d arrays will be appended into a new 1-d array.
Use column_stack to get a 2-d array from 1-d arrays.
If some arrays are already 2-d, then the 1-d arrays need to have a dimension
added to the end (
\emph on
e.g.
\emph default
\family typewriter
y[:,newaxis]
\family default
) in order to stack correctly.
\end_layout
\begin_layout Description
column_stack
\begin_inset LatexCommand index
name "column\\_stack"
\end_inset
(seq)
\end_layout
\begin_layout Description
\InsetSpace ~
Stack a sequence of arrays as columns into a 2-d array.
1-d arrays are converted to 2-d arrays and transposed.
All arrays must have shapes so that the resulting array is well defined.
Compare with
\series bold
hstack
\series default
.
\end_layout
\begin_layout Description
row_stack
\begin_inset LatexCommand index
name "row\\_stack"
\end_inset
(seq)
\end_layout
\begin_layout Description
\InsetSpace ~
Stack a sequence of 1-d arrays as rows into a 2-d array (alias for
\series bold
vstack
\series default
).
\end_layout
\begin_layout Description
dstack
\begin_inset LatexCommand index
name "dstack"
\end_inset
(seq)
\end_layout
\begin_layout Description
\InsetSpace ~
Stack a sequence of arrays along the third axis (depth wise).
Arrays in seq must have the same shape along all dimensions but the third.
Rebuilds array divided by vsplit.
\end_layout
\begin_layout Description
array_split
\begin_inset LatexCommand index
name "array\\_split"
\end_inset
(ary, i_or_s, axis=0)
\end_layout
\begin_layout Description
\InsetSpace ~
Divide ary into a list of sub-arrays along the specified axis.
The i_or_s argument stands for indices_or_sections.
If i_or_s is an integer, ary is divided into that many equally-sized arrays.
If it is impossible to make an even split, each of the leading arrays in
the returned list have one additional member.
If i_or_s is a list of sorted integer, its entries define the indexes where
ary is split.
An empty list for i_or_s results in a single sub-array equal to the original
array.
\end_layout
\begin_layout Description
split
\begin_inset LatexCommand index
name "split"
\end_inset
(ary, i_or_s, axis=0)
\end_layout
\begin_layout Description
\InsetSpace ~
The same as array_split() except if i_or_s is an integer and it is impossible
to make an even split, an error is raised.
\end_layout
\begin_layout Description
hsplit
\begin_inset LatexCommand index
name "hsplit"
\end_inset
(ary, i_or_s)
\end_layout
\begin_layout Description
\InsetSpace ~
Split a single array into multiple columns of sub-arrays (along the first
axis if 1-d or along the second second if >1-d).
Only works on arrays of 1 or more dimension.
\end_layout
\begin_layout Description
vsplit
\begin_inset LatexCommand index
name "vsplit"
\end_inset
()
\end_layout
\begin_layout Description
\InsetSpace ~
Split a single array into multiple rows of sub-arrays (along the first
axis).
Only works on arrays of 2 or more dimensions.
\end_layout
\begin_layout Description
dsplit
\begin_inset LatexCommand index
name "dsplit"
\end_inset
()
\end_layout
\begin_layout Description
\InsetSpace ~
Split a single array into multiple sub-arrays along the third axis (depth).
Only works on arrays of 3 or more dimensions.
\end_layout
\begin_layout Description
apply_along_axis
\begin_inset LatexCommand index
name "apply\\_along\\_axis"
\end_inset
(func1d, axis, arr, *args)
\end_layout
\begin_layout Description
\InsetSpace ~
Execute func1d(arr[sel_i], *args) where func1d takes 1-d arrays and arr
is an N-d array, where sel_i is a selection object sufficient to select
a 1-d sub-array along the given axis.
The function is executed for all 1-d arrays along axis in arr.
\end_layout
\begin_layout Description
apply_over_axes
\begin_inset LatexCommand index
name "apply\\_over\\_axes"
\end_inset
(func, a, axes)
\end_layout
\begin_layout Description
\InsetSpace ~
For each axis in the axes sequence, call func as
\family typewriter
res=func(a, axis)
\family default
.
If res is the same shape as a then set
\family typewriter
a=res
\family default
and continue.
if
\family typewriter
res.ndim = a.ndim -1
\family default
, then insert a dimension before axis and continue.
\end_layout
\begin_layout Description
expand_dims
\begin_inset LatexCommand index
name "expand\\_dims"
\end_inset
(a, axis)
\end_layout
\begin_layout Description
\InsetSpace ~
Expand the shape of array a by including newaxis
\series bold
before
\series default
the given axis.
\end_layout
\begin_layout Description
resize
\begin_inset LatexCommand index
name "resize"
\end_inset
(a, new_shape)
\end_layout
\begin_layout Description
\InsetSpace ~
Returns a new array with the specified shape which can be any size.
The new array is filled with repeated copies of a.
This function is similar in spirit to a.resize(new_shape) except that it
fills in the new array with repeated copies and returns a new array.
\end_layout
\begin_layout Description
kron
\begin_inset LatexCommand index
name "kron"
\end_inset
(a, b)
\end_layout
\begin_layout Description
\InsetSpace ~
Return a composite array with blocks from
\emph on
b
\emph default
scaled by elements of
\emph on
a
\emph default
.
The number of dimensions of
\emph on
a
\emph default
and
\emph on
b
\emph default
should be the same.
If not, then the input with fewer dimensions is pre-pended with ones (broadcast
) to the same shape as the input with more dimensions.
The return array has this same number of dimensions with shape given by
the product of the shape of
\emph on
a
\emph default
and the shape of
\emph on
b
\emph default
.
If either a or b is a scalar then this function is equivalent to multiply(a,b).
\end_layout
\begin_layout Description
\InsetSpace ~
For example, if
\emph on
a
\emph default
and
\emph on
b
\emph default
are is 1-d the result is
\begin_inset Formula \[
\left[\begin{array}{cccc}
a[0]*b & a[1]*b & \cdots & a[-1]*b\end{array}\right]\]
\end_inset
while if
\emph on
a
\emph default
and
\emph on
b
\emph default
are 2-d, the result is
\begin_inset Formula \[
\left[\begin{array}{cccc}
a[0,0]*b & a[0,1]*b & \cdots & a[0,-1]*b\\
a[1,0]*b & a[1,1]*b & \cdots & a[1,-1]*b\\
\vdots & \vdots & \ddots & \vdots\\
a[-1,0]*b & a[-1,1]*b & \cdots & a[-1,-1]*b\end{array}\right]\]
\end_inset
\end_layout
\begin_deeper
\begin_layout Description
Example:
\end_layout
\end_deeper
\begin_layout MyCode
>>> kron([1,10,100],[5,6,7])
\newline
array([ 5, 6, 7, 50, 60, 70, 500, 600,
700])
\newline
>>> kron([[1,10],[100,1000]],[[2,3],[4,5]])
\newline
array([[ 2, 3, 20,
30],
\newline
[ 4, 5, 40, 50],
\newline
[ 200, 300, 2000, 3000],
\newline
[ 400, 500, 4000, 5000]])
\end_layout
\begin_layout Description
tile
\begin_inset LatexCommand index
name "tile"
\end_inset
(a, reps)
\end_layout
\begin_layout Description
\InsetSpace ~
Tile an
\begin_inset Formula $N$
\end_inset
-dimensional array using the shape information in reps to create a larger
\begin_inset Formula $N$
\end_inset
-dimensional array.
This is equivalent to kron(ones(reps, a.dtype), a).
The number of dimensions of a and the length of shape should be the same
or else 1's will be pre-pended to make them the same.
\end_layout
\begin_deeper
\begin_layout Description
Example:
\end_layout
\end_deeper
\begin_layout MyCode
>>> tile([5,6,7],(1,2,3))
\newline
array([[[5, 6, 7, 5, 6, 7, 5, 6, 7],
\newline
[5,
6, 7, 5, 6, 7, 5, 6, 7]]])
\end_layout
\begin_layout Section
Basic functions
\end_layout
\begin_layout Description
average
\begin_inset LatexCommand index
name "average"
\end_inset
(a, axis=None, weights=None, returned=0)
\end_layout
\begin_layout Description
\InsetSpace ~
Computes the average along the indicated axis.
If axis is None, average over the entire array.
Inputs can be integer or floating types; result is type float.
If weights are given, the result is sum(a*weights)/sum(weights).
Therefore, weights must have shape equal to a.shape or be 1-d with length
a.shape[axis].
Integer weights are converted to float.
If returned is True, then return a tuple showing both the result and the
sum of the weights (or count of the values).
The shape of these two results will be the same.
\end_layout
\begin_layout Description
cov
\begin_inset LatexCommand index
name "cov"
\end_inset
(x, y=None, rowvar=1, bias=0)
\end_layout
\begin_layout Description
\InsetSpace ~
Compute the covariance matrix of data in x.
If x is a vector and y is None, then this function is equivalent to asarray(x).v
ar().
Otherwise, x is interpreted as observations of several random variables.
If rowvar is True (default), then the variables are in the rows and the
observations of the variables are in the columns.
Otherwise, the variables are in the columns and the observations are in
the rows.
If y is given then it is treated as another variable or set of variables
to be added to x.
By default, a so-called unbiased estimate of the covariance matrix is made.
If bias is non-zero, then a biased normalization factor (with better mean-squar
e error performance) is used instead.
If
\begin_inset Formula $\mathbf{X}$
\end_inset
is a random vector, then the covariance matrix is defined as
\begin_inset Formula \[
\mathbf{C}=E\left[\left(\mathbf{X}-E\mathbf{X}\right)\left(\mathbf{X}-E\mathbf{X}\right)^{H}\right].\]
\end_inset
It can be approximated as
\begin_inset Formula \[
\mathbf{C}\approx\frac{1}{P}\sum_{i=0}^{N-1}\left(\mathbf{x}_{i}-\bar{\mathbf{x}}\right)\left(\mathbf{x}_{i}-\bar{\mathbf{x}}\right)^{H}\]
\end_inset
where
\begin_inset Formula $\mathbf{x}_{i}$
\end_inset
is an observation of
\begin_inset Formula $\mathbf{X}$
\end_inset
(as a column-vector),
\begin_inset Formula $N$
\end_inset
is the number of observations made and
\begin_inset Formula $P=N-1$
\end_inset
for an unbiased estimate or
\begin_inset Formula $P=N$
\end_inset
for a biased (but lower mean-squared error) estimate.
\end_layout
\begin_layout Description
corrcoef
\begin_inset LatexCommand index
name "corrcoef"
\end_inset
(x, y=None, rowvar=1, bias=0)
\end_layout
\begin_layout Description
\InsetSpace ~
Estimate the correlation coefficient of x.
By default, each row of x contains a random variable with observations
of the random variable in the columns of x.
(If rowvar is False, the each column is a random variable with observations
in the rows).
The y argument can be used to append additional variables to x.
The
\begin_inset Formula $i^{\textrm{th}}$
\end_inset
row and
\begin_inset Formula $j^{\textrm{th}}$
\end_inset
column of the correlation coefficient matrix is defined as
\begin_inset Formula \[
\rho_{ij}=\frac{C_{ij}}{\sqrt{C_{ii}C_{jj}}}\]
\end_inset
where
\begin_inset Formula $\mathbf{C}$
\end_inset
is the covariance matrix.
The rowvar and bias arguments are passed on to the cov function to estimate
\begin_inset Formula $\mathbf{C}.$
\end_inset
\end_layout
\begin_layout Description
msort
\begin_inset LatexCommand index
name "msort"
\end_inset
(a)
\end_layout
\begin_layout Description
\InsetSpace ~
Return a new array, sorted along the first axis.
Equivalent to b=a.copy(); b.sort(0)
\end_layout
\begin_layout Description
median
\begin_inset LatexCommand index
name "median"
\end_inset
(m)
\end_layout
\begin_layout Description
\InsetSpace ~
Returns the median of m along its first dimension.
\end_layout
\begin_layout Description
bincount
\begin_inset LatexCommand index
name "bincount"
\end_inset
(list=, weights=None)
\end_layout
\begin_layout Description
\InsetSpace ~
The list argument is a 1-d integer array.
Let
\begin_inset Formula $r$
\end_inset
be the returned 1-d array whose length is (list.max()+1).
If weights is None, then
\begin_inset Formula $r[i]$
\end_inset
is the number of occurrences of
\begin_inset Formula $i$
\end_inset
in list.
If weight is present, then the
\begin_inset Formula $i^{\textrm{th}}$
\end_inset
element is
\begin_inset Formula \[
r[i]=\sum_{j:\textrm{list}\left[j\right]=i}\textrm{weights}[j].\]
\end_inset
Notice that if weights is None, it is equivalent to a weights array of
all 1.
The length of weights must be the same as the length of list.
\end_layout
\begin_layout Description
digitize
\begin_inset LatexCommand index
name "digitize"
\end_inset
(x=,bins=)
\end_layout
\begin_layout Description
\InsetSpace ~
Return an array of integers the same length as x with values
\begin_inset Formula $i$
\end_inset
such that
\begin_inset Formula $\textrm{bins}\left[i-1\right]\leq x<\textrm{bins}\left[i\right]$
\end_inset
if bins is monotonically increasing, or
\begin_inset Formula $\textrm{bins}[i]\leq x<\textrm{bins}[i-1]$
\end_inset
if bins is monotonically decreasing.
When
\begin_inset Formula $x$
\end_inset
is beyond the bounds of bins, return either
\begin_inset Formula $i=0$
\end_inset
or
\begin_inset Formula $i=$
\end_inset
len(bins) as appropriate.
\end_layout
\begin_layout Description
histogram
\begin_inset LatexCommand index
name "histogram"
\end_inset
(x=, bins=None, range=None, normed=0)
\end_layout
\begin_layout Description
\InsetSpace ~
Construct a histogram for the data in x (treated as one-dimensional array
of type float).
If bins is not a sequence, then bins should be the number of bins which
will be constructed ranging from range[0] to range[1] or x.min() to x.max()
if range is None.
If normed is True, then the histogram will be normalized and comparable
with a probability density function, otherwise it will be a count of the
number of items in each bin.
The return value is the tuple (n, bins) where n is the histogram.
\end_layout
\begin_layout Description
histogram2d
\begin_inset LatexCommand index
name "histogram2d"
\end_inset
(x, y, bins=10, range=None, normed=False)
\end_layout
\begin_layout Description
\InsetSpace ~
Compute the two-dimensional histogram for a dataset (x,y) given the bins.
Returns (histogram, xedges, yedges).
The bins argument can be either the number of bins or a sequence of the
bin edges if the x and y directions should have the same bins.
If the bins argument is a sequence of length 2, then separate bin edges
will be computed.
The first element can be either the number of bins or the bin edges for
the x-direction.
The second element is interpreted as the number of bins or the bin edges
for the y-direction.
The returned histogram array, H, is a count of the number of samples in
each bin.
The array is oriented such that H[i,j] is the number of samples falling
into binx[j] and biny[i] (notice the association x<->j and y<->i).
Setting normed to True returns a density rather than a bin-count.
The range argument allows specifying lower and upper bin edges (in a sequence
of length 2 with 2-length sequences in each entry).
The default is [[x.min(), x.max()],[y.min(), y.max()]].
\end_layout
\begin_layout Description
histogramdd
\begin_inset LatexCommand index
name "histogramdd"
\end_inset
(sample, bins=10, range=None, normed=False)
\end_layout
\begin_layout Description
\InsetSpace ~
Compute the
\begin_inset Formula $D$
\end_inset
-dimensional histogram for a (vector) dataset contained in sample give the
bins.
The dataset is a sequence of
\begin_inset Formula $D$
\end_inset
arrays or an
\begin_inset Formula $N\times D$
\end_inset
array where
\begin_inset Formula $N$
\end_inset
is the number of samples and
\begin_inset Formula $D$
\end_inset
is the number of dimensions.
Returns (histogram, edges) where histogram is a
\begin_inset Formula $D$
\end_inset
-dimensional array of shape given by the number of bins selected in each
axis containing the number of counts that a point in the sample data fell
into the volume bin specified.
The edges sequence has
\begin_inset Formula $D$
\end_inset
-entries to specify the edge boundaries for each dimension.
The bins argument is a sequence of edge arrays or a sequence of the number
of bins.
If a scalar is given, it is assumed to be the number of bins for all dimensions.
The range is a length-
\begin_inset Formula $D$
\end_inset
sequence containing lower and upper bin edges which default to the min
and maximum of the respective datasets.
If normed is True, then a density rather than a bin-count is returned.
\end_layout
\begin_layout Description
logspace
\begin_inset LatexCommand index
name "logspace"
\end_inset
(start, stop, num=50, endpoint=True,base=10.0)
\end_layout
\begin_layout Description
\InsetSpace ~
Evenly spaced samples on a logarithmic scale.
Returns num evenly spaced (in logspace) samples from base**start to base**stop.
If endpoint is True, then the last sample is base**stop.
\end_layout
\begin_layout Description
linspace
\begin_inset LatexCommand index
name "linspace"
\end_inset
(start, stop, num=50, endpoint=True, retstep=False):
\end_layout
\begin_layout Description
\InsetSpace ~
Evenly spaced samples.
Returns num evenly spaced samples from start to stop.
If endpoint is True, then the last sample is stop.
If retstep is True, then return the computed step size.
\end_layout
\begin_layout Description
meshgrid
\begin_inset LatexCommand index
name "meshgrid"
\end_inset
(x, y)
\end_layout
\begin_layout Description
\InsetSpace ~
For 1-d arrays x, y with lengths Nx=len(x) and Ny = len(y), return X, Y
where X and Y are (Ny, Nx) shaped arrays with the elements of x and y repeated
to fill the array.
\end_layout
\begin_layout MyCode
>>> X,Y = meshgrid([1,2,3], [4,5,6,7]); print X; print Y
\newline
[[1 2 3]
\newline
[1 2 3]
\newline
[1 2 3]
\newline
[1 2 3]]
\newline
[[4 4 4]
\newline
[5 5 5]
\newline
[6 6 6]
\newline
[7 7 7]]
\end_layout
\begin_layout Description
select
\begin_inset LatexCommand index
name "select"
\end_inset
(condlist, choicelist, default=0)
\end_layout
\begin_layout Description
\InsetSpace ~
Returns an array comprised from different elements of choicelist depending
on the list of conditions.
The condlist argument is a list of Boolean condition arrays.
The choicelist argument is a list of choice arrays (of the same size as
the arrays in condlist).
The result has the same size as the arrays in choicelist.
If condlist is [
\begin_inset Formula $c_{0},\ldots,c_{N-1}$
\end_inset
], then choicelist must be of length
\begin_inset Formula $N$
\end_inset
.
The elements of choicelist can then be represented as [
\begin_inset Formula $v_{0},\ldots,v_{N-1}$
\end_inset
].
The default choice if none of the conditions are met is given as the default
argument.
The conditions are tested in order and the first one satisfied is used
to select the choice.
In other words, the elements of the output array are found from the following
tree (evaluated on an element-by-element basis)
\end_layout
\begin_layout LyX-Code
\series bold
if
\series default
\begin_inset Formula $c_{0}$
\end_inset
:
\begin_inset Formula $v_{0}$
\end_inset
\newline
\series bold
elif
\series default
\begin_inset Formula $c_{1}$
\end_inset
:
\begin_inset Formula $v_{1}$
\end_inset
\newline
...
\newline
\series bold
elif
\series default
\begin_inset Formula $c_{N-1}$
\end_inset
:
\begin_inset Formula $v_{N-1}$
\end_inset
\newline
\series bold
else
\series default
: default
\end_layout
\begin_layout Description
piecewise
\begin_inset LatexCommand index
name "piecewise"
\end_inset
(x, condlist, funclist, *args, **kw)
\end_layout
\begin_layout Description
\InsetSpace ~
Compute a piecewise-defined function.
A piecewise defined function is
\begin_inset Formula \[
f\left(x\right)=\left\{ \begin{array}{cc}
f_{1}\left(x\right) & x\in S_{1},\\
f_{2}\left(x\right) & x\in S_{2},\\
\vdots & \vdots\\
f_{n}\left(x\right) & x\in S_{n}.\end{array}\right.\]
\end_inset
where
\begin_inset Formula $S_{1}$
\end_inset
are sets.
Thus, the function is defined differently over different sub-domains of
the input.
Such a function can be computed using
\family typewriter
select
\family default
but such an implementation means calling each
\begin_inset Formula $f_{i}$
\end_inset
over the entire region of
\begin_inset Formula $x.$
\end_inset
The piecewise call guarantees that each function
\begin_inset Formula $f_{i}$
\end_inset
will only be called over those values of
\begin_inset Formula $x$
\end_inset
in
\begin_inset Formula $S_{i}.$
\end_inset
\end_layout
\begin_layout Description
\InsetSpace ~
Arguments: x is the array of values over which to call the function; condlist
is a sequence of Boolean (indicator) arrays (or a single Boolean array)
of the same shape as
\begin_inset Formula $x$
\end_inset
that defines the sets (True indicates that element of
\begin_inset Formula $x$
\end_inset
is in the set).
If needed, to match the length of funclist, an
\begin_inset Quotes eld
\end_inset
otherwise
\begin_inset Quotes erd
\end_inset
set will be added to condlist.
This otherwise set is defined as
\begin_inset Formula $S_{n}=\overline{\bigcup S_{i}}.$
\end_inset
The argument funclist is a list of functions to be called (or items to
be inserted) corresponding to the conditions.
Each of these functions can take extra arguments and key-word arguments
which are passed in as *args, and **kw using standard Python syntax.
Each of these functions should return vector output for vector input.
If the function is a scalar, then it will simply be inserted where appropriate
into the output.
It is the equivalent of a constant function.
\end_layout
\begin_deeper
\begin_layout Description
Example: Suppose we want to compute
\begin_inset Formula $f\left(x\right)=x^{2}\Pi\left(\frac{x}{3}\right)+u\left(x-5\right)$
\end_inset
where
\begin_inset Formula $\Pi\left(x\right)=1$
\end_inset
only when
\begin_inset Formula $\left|x\right|\leq1$
\end_inset
and
\begin_inset Formula $u\left(x\right)=1$
\end_inset
only when
\begin_inset Formula $x\geq0.$
\end_inset
This could be done using the code:
\end_layout
\end_deeper
\begin_layout MyCode
>>> f1 = lambda x: x*x
\newline
>>> x = r_[-4:6:20j]
\newline
>>> y = piecewise(x,abs(x)<=3,[f1,0])+
piecewise(x,x>=0,[1,0])
\newline
>>> set_printoptions(precision=4); print y
\newline
[ 0.
0.
8.687 5.8615 3.59 1.8726 0.7091 0.0997
\newline
1.0443 1.5429 2.5956 4.2022
6.3629 9.0776 1.
1.
1.
\newline
1.
1.
1.
]
\end_layout
\begin_layout Description
trim_zeros
\begin_inset LatexCommand index
name "trim\\_zeros"
\end_inset
(filt, trim='fb'):
\end_layout
\begin_layout Description
\InsetSpace ~
Trim the leading ('f' in trim) and trailing ('b' in trim) zeros from a
sequence according to the trim keyword.
\end_layout
\begin_layout Description
trapz
\begin_inset LatexCommand index
name "trapz"
\end_inset
(y, x=None, dx=1.0, axis=-1)
\end_layout
\begin_layout Description
\InsetSpace ~
If
\begin_inset Formula $\mathbf{y}$
\end_inset
contains samples of a function:
\begin_inset Formula $y_{i}=f\left(x_{i}\right)$
\end_inset
then trapz can be used to approximate the integral of the function using
the trapezoidal rule.
If the sampling is not evenly spaced use
\begin_inset Formula $\mathbf{x}$
\end_inset
to pass in the sample positions.
Otherwise, only the sample-spacing is needed in dx.
The trapz function can work with many functions at a time stored in an
\begin_inset Formula $N$
\end_inset
-dimensional array.
The axis argument controls which axis defines the sampling axis (the other
dimensions are different functions).
The number of dimensions of the returned result is
\begin_inset Formula $y$
\end_inset
.ndim - 1.
\end_layout
\begin_layout Description
diff
\begin_inset LatexCommand index
name "diff"
\end_inset
(x, n=1, axis=-1)
\end_layout
\begin_layout Description
\InsetSpace ~
Calculates the
\begin_inset Formula $n^{\textrm{th}}$
\end_inset
order, discrete difference along the given axis.
\end_layout
\begin_layout Description
gradient
\begin_inset LatexCommand index
name "gradient"
\end_inset
(f, *varargs)
\end_layout
\begin_layout Description
\InsetSpace ~
Calculate the gradient of an N-d scalar function, f.
Uses central differences on the interior and first differences on boundaries
to give the same shape for each component of the gradient.
The varargs variable can contain 0, 1, or N scalars corresponding to the
sample distances in each direction (default 1.0).
If f is N-d, then N arrays are returned each of the same shape as f, giving
the derivative of f with respect to each dimension.
\end_layout
\begin_layout Description
angle
\begin_inset LatexCommand index
name "angle"
\end_inset
(z, deg=0)
\end_layout
\begin_layout Description
\InsetSpace ~
Return the angle of a complex number z (in degrees if deg is True).
\end_layout
\begin_layout Description
unwrap
\begin_inset LatexCommand index
name "unwrap"
\end_inset
(p, discont=pi, axis=-1)
\end_layout
\begin_layout Description
\InsetSpace ~
Unwraps radian phase p by changing absolute jumps greater than discont
to their
\begin_inset Formula $2\pi$
\end_inset
complement along the given axis.
\end_layout
\begin_layout Description
sort_complex
\begin_inset LatexCommand index
name "sort\\_complex"
\end_inset
(x)
\end_layout
\begin_layout Description
\InsetSpace ~
This is syntactic sugar for asarray(x).sort().astype() where
cmplx_type is csingle if x.dtype is integral with fewer bits than intp,
clongfloat if x.dtype.type is longfloat, and cdouble for all other types.
The sorting is done by comparing the real part of the array, and then the
imaginary part if the real parts are the same.
\end_layout
\begin_layout Description
disp
\begin_inset LatexCommand index
name "disp"
\end_inset
(mesg, device=None, linefeed=1)
\end_layout
\begin_layout Description
\InsetSpace ~
Display a message to device (defaults to sys.stdout) with or without a closing
linefeed.
\end_layout
\begin_layout Description
unique
\begin_inset LatexCommand index
name "unique"
\end_inset
(seq)
\end_layout
\begin_layout Description
\InsetSpace ~
Returns unique items in the 1-dimensional seq.
\end_layout
\begin_layout Description
extract
\begin_inset LatexCommand index
name "extract"
\end_inset
(condition, arr)
\end_layout
\begin_layout Description
\InsetSpace ~
Equivalent to arr.compress(condition.flat) and arr.flat[bool_(condition.flat)]
which extracts the elements of (flattened) arr according to the elements
of (flattened) condition that are True.
\end_layout
\begin_layout Description
place
\begin_inset LatexCommand index
name "place"
\end_inset
(arr, mask, vals)
\end_layout
\begin_layout Description
\InsetSpace ~
Inverse of extract.
Equivalent to arr[abool(mask)] = vals but it uses a different algorithm.
\end_layout
\begin_layout Description
delete
\begin_inset LatexCommand index
name "delete"
\end_inset
(arr, indices, axis=None)
\end_layout
\begin_layout Description
\InsetSpace ~
Return a new array with the sub-arrays indicated by indices along axis
removed.
If axis is None, then first ravel the array and set axis to -1.
The indices argument describes which sub-arrays along the given axis should
be removed.
It can be an integer, a slice object, or a sequence of integers.
A new array is created with the corresponding sub-arrays are removed.
\end_layout
\begin_layout Description
insert
\begin_inset LatexCommand index
name "insert"
\end_inset
(arr, indices, values, axis=None)
\end_layout
\begin_layout Description
\InsetSpace ~
Create a new array with values inserted into arr before indices.
If axis is None, then first ravel the array and set axis to -1.
The indices argument describes which indices along the provided axis the
values should be inserted before.
It can be an integer, a slice object, or a sequence of integers.
The values argument must be broadcastable to the shape implied by where
they will be inserted.
\end_layout
\begin_layout Description
append
\begin_inset LatexCommand index
name "append"
\end_inset
(arr, values, axis=None)
\end_layout
\begin_layout Description
\InsetSpace ~
Return a new array with values appended to the end of the array along axis.
\end_layout
\begin_layout Description
nansum
\begin_inset LatexCommand index
name "nansum"
\end_inset
(x, axis=None)
\end_layout
\begin_layout Description
nanmax
\begin_inset LatexCommand index
name "nanmax"
\end_inset
(x, axis=None)
\end_layout
\begin_layout Description
nanargmax
\begin_inset LatexCommand index
name "nanargmax"
\end_inset
(x, axis=None)
\end_layout
\begin_layout Description
nanargmin
\begin_inset LatexCommand index
name "nanargmin"
\end_inset
(x, axis=None)
\end_layout
\begin_layout Description
nanmin
\begin_inset LatexCommand index
name "nanmin"
\end_inset
(x, axis=None)
\end_layout
\begin_layout Description
\InsetSpace ~
These functions perform their respective operations over the given axis
(or the entire array if axis is None), after replacing any nans with appropriat
e values so as not to affect the calculation.
\end_layout
\begin_layout Description
vectorize
\begin_inset LatexCommand index
name "vectorize"
\end_inset
(pyfunc, otypes=None, doc=None)
\end_layout
\begin_layout Description
\InsetSpace ~
This creates a class whose instances have a call method that invokes a
ufunc that has been dynamically built to call the python function pyfunc
internally.
The output types can be controlled by the otypes argument.
If it is None, then the output types will be determined upon first call
to the function using the provided inputs.
This can be reset, by re-setting the otypes attribute to
\begin_inset Quotes eld
\end_inset
\begin_inset Quotes erd
\end_inset
.
The normal rules of array broadcasting are followed by the returned object.
\end_layout
\begin_layout MyCode
>>> def myfunc(a,b):
\newline
...
if (a>b): return a
\newline
...
else: return b-1
\newline
>>> vecfunc = vectorize(myfunc)
\newline
>>> vecfunc([[1,2,3],[5,6,9]
],[7,4,5])
\newline
array([[6, 3, 4],
\newline
[6, 6, 9]])
\end_layout
\begin_layout Description
asarray_chkfinite
\begin_inset LatexCommand index
name "asarray\\_chkfinite"
\end_inset
(x)
\end_layout
\begin_layout Description
\InsetSpace ~
Like asarray(x) except an error is raised if any of the values in x are
not finite.
\end_layout
\begin_layout Description
round_
\begin_inset LatexCommand index
name "round\\_"
\end_inset
(x, decimals=0)
\end_layout
\begin_layout Description
\InsetSpace ~
Return an array with all the elements of x rounded to decimals places.
Returns x if array is not floating point and rounds both the real and imaginary
parts separately if array is complex.
Rounds in the same way as standard python except for half-way values are
rounded to the nearest
\emph on
even
\emph default
number.
\end_layout
\begin_layout Description
packbits (array, axis=None)
\end_layout
\begin_layout Description
\InsetSpace ~
Pack an integer array of logical data (zero/non-zero) into bits of a uint8
data-type along the dimension given by axis.
This dimension is shrunk by a factor of 8 (rounded up).
Each element in the input is converted to a bit in the output which is
set to 1 or 0 depending on whether the input is non-zero or not.
Thus, every 8-element chunk of the input is converted to a single byte
in the output.
If axis is None, then the bit-packing is done on the entire array as if
it were raveled.
\end_layout
\begin_layout Description
unpackbits (array, axis=None)
\end_layout
\begin_layout Description
\InsetSpace ~
Unpack bits of an array of uint8 data-type into a single uint8 byte for
each bit along the dimension given by axis.
This dimension is thus expanded 8-fold, but otherwise the output has the
same shape as the input.
If axis is None, then the input is treated as a 1-d array and expanded
8-fold so that each bit of the input is given an output byte.
\end_layout
\begin_layout Description
add_docstring
\begin_inset LatexCommand index
name "add\\_docstring"
\end_inset
(obj, doc)
\end_layout
\begin_layout Description
\InsetSpace ~
Adds a docstring to a built-in object, obj, that does not have a docstring
defined already.
The obj can be a built-in function-or-method, a typeobject, a method descriptor
, a getset descriptor, or a member descriptor.
This is useful for improving the documentation of objects defined in C-compiled
code without re-compiling.
If the object already has a docstring, a RuntimeError is raised.
If the object is not a supported type the code can add a docstring to,
a TypeError is raised.
\end_layout
\begin_layout Description
add_newdoc
\begin_inset LatexCommand index
name "add\\_newdoc"
\end_inset
(place, obj, doc)
\end_layout
\begin_layout Description
\InsetSpace ~
Adds a docstring to the
\emph on
obj
\emph default
imported from
\emph on
place
\emph default
using exec 'from %s import %s' % (place, obj).
Thus, both place and obj should be strings.
If doc is a string, then a single docstring is added to obj from place.
If doc is a 2-tuple, then obj must be an object with attributes that need
to be commented.
The first element of the doc tuple is the attribute to be commented on
and the second element is the actual docstring.
If doc is a list, then it must be composed of elements that are 2-tuples
indicating that obj has several attributes that need to be documented.
\end_layout
\begin_layout Section
Polynomial functions
\end_layout
\begin_layout Standard
There are two interfaces for dealing with polynomials
\begin_inset LatexCommand index
name "polynomials"
\end_inset
: a class-based interface, and a collection of functions to deal with a
polynomials represented as a simple list of coefficients.
This latter representation results from the is a one-to-one correspondence
between a length-
\begin_inset Formula $\left(n+1\right)$
\end_inset
sequence of coefficients
\begin_inset Formula $a_{n}\equiv a[n]$
\end_inset
and an
\begin_inset Formula $n^{\textrm{th}}$
\end_inset
order polynomial:
\begin_inset Formula \[
p\left(x\right)=a_{0}x^{n}+a_{1}x^{n-1}+\cdots+a_{n-1}x+a_{n}.\]
\end_inset
Most of the functions below operate on and return a simple sequence of
coefficients representing a polynomial.
There is, however, a simple polynomial class that provides some utility
for doing simple algebra on polynomials.
\end_layout
\begin_layout Description
poly1d
\begin_inset LatexCommand index
name "poly1d"
\end_inset
(c_or_r, r=0)
\end_layout
\begin_layout Description
\InsetSpace ~
This construction returns an instance of a simple polynomial class.
It can take either a list of coefficients on polynomial powers, or a sequence
of roots (if r=1).
The returned polynomial can be added, subtracted, multiplied, divided,
and taken to integer powers, resulting in new polynomials.
\end_layout
\begin_deeper
\begin_layout Description
.r roots of the polynomial
\end_layout
\begin_layout Description
.o order of the polynomial
\end_layout
\begin_layout Description
.c polynomial coefficients as an array (also
\series bold
__array__()
\series default
)
\end_layout
\begin_layout Description
__call__(x) evaluate the polynomial at x (can be an array)
\end_layout
\begin_layout Description
__getitem__(x) p[k] returns the coefficient on the kth power of x (backwards
from indexing the coefficient array)
\end_layout
\end_deeper
\begin_layout MyCode
>>> p=poly1d([2,5,7])
\newline
>>> print p
\newline
2
\newline
2 x + 5 x + 7
\newline
>>> print p*[1,3,1]
\newline
4
3 2
\newline
2 x + 11 x + 24 x + 26 x + 7
\newline
>>> print p([0.5,0.6,3])
\newline
[ 10.
10.72 40.
]
\newline
>>> print p.r
\newline
[-1.25+1.3919j -1.25-1.3919j]
\end_layout
\begin_layout Description
poly
\begin_inset LatexCommand index
name "poly"
\end_inset
(roots_or_matrix)
\end_layout
\begin_layout Description
\InsetSpace ~
Return a sequence of coefficients representing a polynomial given the sequence
of roots as an argument.
Alternatively, if the argument is a 2-d array, then return the characteristic
polynomial of the matrix.
\end_layout
\begin_layout Description
roots
\begin_inset LatexCommand index
name "roots"
\end_inset
(poly)
\end_layout
\begin_layout Description
\InsetSpace ~
Return the roots of the polynomial represented by coefficients in poly
\end_layout
\begin_layout Description
polyint
\begin_inset LatexCommand index
name "polyint"
\end_inset
(poly, m=1, k=None)
\end_layout
\begin_layout Description
\InsetSpace ~
Return an exact
\begin_inset Formula $m^{\textrm{th}}$
\end_inset
-order integral of the polynomial represented in poly.
If k is None, then use 0 for the integrating constants.
Otherwise, use the scalars in the sequence k as integrating constants.
Also available as .integ (m=1,k=0) method of poly1d objects.
\end_layout
\begin_deeper
\begin_layout Description
Example:
\begin_inset Formula \begin{eqnarray*}
p\left(x\right) & = & x^{2}+3x+4\\
\int\int p\left(x\right) & = & \frac{1}{12}x^{4}+\frac{1}{2}x^{3}+2x^{2}+k_{0}x+k_{1}\end{eqnarray*}
\end_inset
\end_layout
\end_deeper
\begin_layout MyCode
>>> print polyint([1,3,4],m=2,k=[5,3])
\newline
[ 0.0833 0.5 2.
5.
3.
]
\end_layout
\begin_layout Description
polyder
\begin_inset LatexCommand index
name "polyder"
\end_inset
(poly, m)
\end_layout
\begin_layout Description
\InsetSpace ~
Return an exact
\begin_inset Formula $m^{\textrm{th}}$
\end_inset
-order derivative of the polynomial represented in poly.
Also available as .deriv(m=1) method of poly1d objects.
\end_layout
\begin_deeper
\begin_layout Description
Example:
\begin_inset Formula \begin{eqnarray*}
p\left(x\right) & = & x^{3}+2x^{2}+4x+3\\
\frac{dp}{dx}\left(x\right) & = & 3x^{2}+4x+4\end{eqnarray*}
\end_inset
\end_layout
\end_deeper
\begin_layout MyCode
>>> polyder([1,2,4,3])
\newline
array([3, 4, 4])
\end_layout
\begin_layout Description
polyadd
\begin_inset LatexCommand index
name "polyadd"
\end_inset
(p1, p2)
\end_layout
\begin_layout Description
\InsetSpace ~
Add the two polynomials represented by coefficients:
\begin_inset Formula $p_{1}\left(x\right)+p_{2}\left(x\right)$
\end_inset
\end_layout
\begin_layout Description
polysub
\begin_inset LatexCommand index
name "polysub"
\end_inset
(p1, p2)
\end_layout
\begin_layout Description
\InsetSpace ~
Return coefficients for the polynomial found by subtracting the two polynomials
represented by
\begin_inset Formula $p_{1}$
\end_inset
and
\begin_inset Formula $p_{2}$
\end_inset
:
\begin_inset Formula $p_{1}\left(x\right)-p_{2}\left(x\right)$
\end_inset
\end_layout
\begin_layout Description
polymul
\begin_inset LatexCommand index
name "polymul"
\end_inset
(p1, p2)
\end_layout
\begin_layout Description
\InsetSpace ~
Return the coefficients for
\begin_inset Formula $p_{1}\left(x\right)p_{2}\left(x\right)$
\end_inset
\end_layout
\begin_layout Description
polydiv
\begin_inset LatexCommand index
name "polydiv"
\end_inset
(p1, p2)
\end_layout
\begin_layout Description
\InsetSpace ~
Return the quotient,
\begin_inset Formula $q\left(x\right)$
\end_inset
, and remainder,
\begin_inset Formula $r\left(x\right)$
\end_inset
, so that
\begin_inset Formula $p_{1}\left(x\right)=q\left(x\right)p_{2}\left(x\right)+r\left(x\right),$
\end_inset
with the order of
\begin_inset Formula $r\left(x\right)$
\end_inset
less than the order of
\begin_inset Formula $p_{2}\left(x\right).$
\end_inset
\end_layout
\begin_layout Description
polyval
\begin_inset LatexCommand index
name "polyval"
\end_inset
(p, y)
\end_layout
\begin_layout Description
\InsetSpace ~
Evaluate the polynomial
\begin_inset Formula $p$
\end_inset
at
\begin_inset Formula $y$
\end_inset
.
The argument,
\begin_inset Formula $y$
\end_inset
, can be a number or an array or a polynomial object.
If x is a polynomial object, then polyval performs polynomial composition:
\begin_inset Formula $p\left(y\left(x\right)\right),$
\end_inset
otherwise polyval computes the value of the polynomial at each
\begin_inset Formula $y$
\end_inset
.
Uses Horner's rule for evaluation, but this can still lead to numerical
instabilities for wildly fluctuating coefficients.
\end_layout
\begin_layout Description
polyfit
\begin_inset LatexCommand index
name "polyfit"
\end_inset
(x,y,N)
\end_layout
\begin_layout Description
\InsetSpace ~
Compute a best-fit polynomial in
\begin_inset Formula $x$
\end_inset
of order
\begin_inset Formula $N$
\end_inset
, to the data,
\begin_inset Formula $y$
\end_inset
, in the sense of minimizing averaged-squared error between the measurement
and the model.
Useful for quick line-fitting
\begin_inset LatexCommand index
name "fitting"
\end_inset
.
\end_layout
\begin_layout Section
Set Operations
\end_layout
\begin_layout Standard
The set operations
\begin_inset LatexCommand index
name "set operations|("
\end_inset
were kindly contributed by Robert Cimrman.
These set operations are based on sorting functions and all expect 1-d
sequences with unique elements with the exception of unique1d and intersect1d_n
u which will flatten N-d nested-sequences to 1-d arrays and can handle non-uniqu
e elements.
\end_layout
\begin_layout Description
unique1d
\begin_inset LatexCommand index
name "unique1d"
\end_inset
(arr, retindx=False)
\end_layout
\begin_layout Description
\InsetSpace ~
Return the unique elements of arr as a 1-d array.
If retindx is True, then also return the indices, ind, such that arr.flat[ind]
is the set of unique values.
\end_layout
\begin_layout Description
intersect1d
\begin_inset LatexCommand index
name "intersect1d"
\end_inset
(a1, a2)
\end_layout
\begin_layout Description
\InsetSpace ~
Return the (sorted) intersection of a1 and a2 which is an array containing
the elements of a1 that are also in a2.
\end_layout
\begin_layout Description
intersect1d_nu
\begin_inset LatexCommand index
name "intersect1d\\_nu"
\end_inset
(a1, a2)
\end_layout
\begin_layout Description
\InsetSpace ~
Return the (sorted) intersection of a1 and a2 but allow a1 and a2 to be
N-d arrays with non-unique elements.
Equivalent to intersect1d(unique1d(a1), unique1d(a2)).
\end_layout
\begin_layout Description
union1d
\begin_inset LatexCommand index
name "union1d"
\end_inset
(a1, a2)
\end_layout
\begin_layout Description
\InsetSpace ~
Return the (sorted) union of a1 and a2 which is an array containing elements
that are in either a1 or a2.
\end_layout
\begin_layout Description
setdiff1d
\begin_inset LatexCommand index
name "setdiff1d"
\end_inset
(a1, a2)
\end_layout
\begin_layout Description
\InsetSpace ~
Return the set-difference of a1 and a2 which is an array containing the
elements of a1 that are
\series bold
not
\series default
in a2.
\end_layout
\begin_layout Description
setxor1d
\begin_inset LatexCommand index
name "setxor1d"
\end_inset
(a1, a2)
\end_layout
\begin_layout Description
\InsetSpace ~
Return the (sorted) set containing the exclusive-or of the arrays a1 and
a2.
The exclusive-or contains elements that are in a1 or in a2 as long as the
element is not in both a1 and a2.
\end_layout
\begin_layout Description
setmember1d
\begin_inset LatexCommand index
name "setmember1d"
\end_inset
(tocheck, set)
\end_layout
\begin_layout Description
\InsetSpace ~
Return a Boolean 1-d array of the length of tocheck which is True whenever
that element is contained in set and false when it is not.
Equivalent
\begin_inset LatexCommand index
name "set operations|)"
\end_inset
to array([x in set for x in tocheck]).
\end_layout
\begin_layout Section
Array construction using index tricks
\end_layout
\begin_layout Standard
The functions and classes in this category make it simpler to construct
arrays.
\end_layout
\begin_layout Description
ix_
\begin_inset LatexCommand index
name "ix\\_"
\end_inset
(*args)
\end_layout
\begin_layout Description
\InsetSpace ~
This indexing cross function is useful for forming indexing arrays necessary
to select out the cross-product of
\begin_inset Formula $N$
\end_inset
1-dimensional arrays.
Note that the default indexing does not do a cross-product (which might
be unexpected for someone coming from other programming environments).
The default indexing is more general purpose.
Using the ix_ constructor can produce the indexing arrays necessary to
select a cross-product.
\end_layout
\begin_layout Description
mgrid [index expression]
\end_layout
\begin_layout Description
\InsetSpace ~
This is an instance of a class.
It can be used to construct a filled
\begin_inset Quotes eld
\end_inset
mesh-grid
\begin_inset Quotes erd
\end_inset
using slicing syntax.
\end_layout
\begin_layout Description
ogrid [index expression]
\end_layout
\begin_layout Description
\InsetSpace ~
This is similar to mgrid except it returns an open grid, so as to save
space and time.
The broadcasting rules will ensure that any universal function operating
on the grid will act as if the ogrid had been the result of mgrid.
\end_layout
\begin_layout Description
r_
\begin_inset LatexCommand index
name "r\\_"
\end_inset
[index expression]
\end_layout
\begin_layout Description
\InsetSpace ~
This is a simple way to build up arrays quickly.
There are two use cases.
1) If the index expression contains comma separated arrays, then stack
them along their first axis.
2) If the index expression contains slice notation or scalars then create
a 1-d array with a range indicated by the slice notation.
In other-words the slice syntax start:stop:step is equivalent to arange(start,
stop, step) inside of the brackets.
However, if step is an imaginary number (i.e.
100j) then its integer portion is interpreted as a number-of-points desired
and the start and stop are inclusive.
In other words start:stop:step
\family typewriter
j
\family default
is interpreted as linspace(start, stop, step, endpoint=1) inside of the
brackets.
After expansion of slice notation, all comma separated sequences are concatenat
ed together.
\end_layout
\begin_layout Description
\InsetSpace ~
Optional character strings placed as the first element of the index expression
can be used to change the output.
The strings 'r' or 'c' result in matrix output.
If the result is 1-d and 'r' is specified a
\begin_inset Formula $1\times N$
\end_inset
(row) matrix is produced.
If the result is 1-d and 'c' is specified, then a
\begin_inset Formula $N\times1$
\end_inset
(column) matrix is produced.
If the result is 2-d then both provide the same matrix result.
\end_layout
\begin_layout MyCode
>>> print r_[-1:1:9j,[0]*10,5,6]
\newline
[-1.
-0.75 -0.5 -0.25 0.
0.25 0.5 0.75 1.
0.
0.
\newline
0.
0.
0.
0.
0.
0.
0.
0.
5.
6.
]
\newline
>>> print r_['r',1,2,5,6]
\newline
[[1 2 5 6]]
\newline
>>> print r_['c',1,2,5,6]
\newline
[[1]
\newline
[2]
\newline
[5]
\newline
[6]]
\end_layout
\begin_layout Description
\InsetSpace ~
A string integer specifies which axis to stack multiple comma separated
arrays along.
\end_layout
\begin_layout MyCode
>>> a=arange(6).reshape(2,3)
\newline
>>> r_[a,a]
\newline
array([[0, 1, 2],
\newline
[3, 4, 5],
\newline
[0, 1, 2],
\newline
[3, 4, 5]])
\newline
>>> r_['-1',a,a]
\newline
array([[0, 1, 2, 0, 1,
2],
\newline
[3, 4, 5, 3, 4, 5]])
\end_layout
\begin_layout Description
\InsetSpace ~
A string of two comma-separated integers allows indication of the minimum
number of dimensions to force each entry into as the second integer (the
axis to concatenate along is still the first integer).
\end_layout
\begin_layout MyCode
>>> r_['0,2',[1,2,3],[4,5,6]]
\newline
array([[1, 2, 3],
\newline
[4, 5, 6]])
\newline
>>> r_['1,2',[1,
2,3],[4,5,6]]
\newline
array([[1, 2, 3, 4, 5, 6]])
\end_layout
\begin_layout Description
\InsetSpace ~
A string with three comma-separated integers allows specification of the
axis to concatenate along, the minimum number of dimensions to force the
entries to, and which axis should contain the start of the arrays which
are less than the specified number of dimensions.
In other words the third integer allows you to specify where the the 1's
should be placed in the shape of the arrays that have their shapes upgraded.
By default, they are placed in the front of the shape tuple.
The third argument allows you to specify where the start of the array should
be instead.
Thus, a third argument of '0' would place the 1's at the end of the array
shape.
Negative integers specify where in the new shape tuple the last dimension
of upgraded arrays should be placed, so the default is '-1'.
\end_layout
\begin_layout MyCode
>>> r_['0,2,0', [1,2,3], [4,5,6]]
\newline
array([[1],
\newline
[2],
\newline
[3],
\newline
[4],
\newline
[5],
\newline
[6]])
\newline
>>> r_['1,2,0', [1,2,3], [4,5,6]]
\newline
array([[1,
4],
\newline
[2, 5],
\newline
[3, 6]])
\end_layout
\begin_layout Description
c_
\begin_inset LatexCommand index
name "c\\_"
\end_inset
[index_expression]
\end_layout
\begin_layout Description
\InsetSpace ~
This is short-hand for r_['-1,2,0', index_expression] useful because of
its common occurence.
In particular, arrays will be stacked along their last axis after being
upgraded to at least 2-d with 1's post-pended to the shape (column vectors
made out of 1-d arrays).
\end_layout
\begin_layout Section
Other indexing devices
\end_layout
\begin_layout Description
index_exp
\begin_inset LatexCommand index
name "index\\_exp"
\end_inset
[index expression]
\end_layout
\begin_layout Description
\InsetSpace ~
Return a tuple of Python objects that implements the index expression and
can be modified and placed in any other index expression.
\end_layout
\begin_layout MyCode
>>> index_exp[2:5,...,4,::-1]
\newline
(slice(2, 5, None), Ellipsis, 4, slice(None, None,
-1))
\end_layout
\begin_layout Description
s_
\begin_inset LatexCommand index
name "s\\_"
\end_inset
[index expression]
\end_layout
\begin_layout Description
\InsetSpace ~
Translate index expressions into the equivalent Python objects.
This is similar to index_expression except a tuple is not always returned.
For example:
\end_layout
\begin_layout MyCode
>>> s_[1:10]
\newline
slice(1, 10, None)
\newline
>>> s_[1:10,-3:4:0.5]
\newline
(slice(1, 10, None), slice(-3,
4, 0.5))
\end_layout
\begin_layout Description
\InsetSpace ~
This provides a standard way to construct index expressions to pass to
functions and methods because Python does not allow slice expressions anywhere
except for inside brackets.
\end_layout
\begin_layout Description
ndindex
\begin_inset LatexCommand index
name "ndindex"
\end_inset
(*seq)
\end_layout
\begin_layout Description
\InsetSpace ~
A sequence of
\begin_inset Formula $N$
\end_inset
integers are passed in as separate arguments.
These integers are used as the upper boundaries of an
\begin_inset Formula $N$
\end_inset
-dimensional counter that starts at 0.
The object returned is an iterator that implements the counter.
\end_layout
\begin_layout MyCode
>>> for index in ndindex(3,3,2):
\newline
...
print index,
\newline
(0, 0, 0) (0, 0, 1) (0, 1, 0) (0, 1, 1) (0, 2, 0) (0, 2,
1) (1, 0, 0) (1, 0, 1) (1, 1, 0) (1, 1, 1) (1, 2, 0) (1, 2, 1) (2, 0, 0)
(2, 0, 1) (2, 1, 0) (2, 1, 1) (2, 2, 0) (2, 2, 1)
\end_layout
\begin_layout Description
unravel_index
\begin_inset LatexCommand index
name "unravel\\_index"
\end_inset
(indx, dims)
\end_layout
\begin_layout Description
\InsetSpace ~
Convert a flat index, indx, into an index tuple for an array of the given
shape.
Keep in mind that it may be more convenient to use indx with a.flat, then
to unravel the index.
\end_layout
\begin_layout Section
Two-dimensional functions
\end_layout
\begin_layout Standard
These functions all deal with or return two dimensional arrays.
\end_layout
\begin_layout Description
eye
\begin_inset LatexCommand index
name "eye"
\end_inset
(
\begin_inset Formula $N$
\end_inset
,
\begin_inset Formula $M$
\end_inset
=None,
\begin_inset Formula $k$
\end_inset
=0, dtype=float)
\end_layout
\begin_layout Description
\InsetSpace ~
Return an
\begin_inset Formula $N\times M$
\end_inset
array of the given type with ones down the
\begin_inset Formula $k^{\textrm{th}}$
\end_inset
diagonal.
If
\begin_inset Formula $M$
\end_inset
is None, it defaults to
\begin_inset Formula $N$
\end_inset
.
Alternatively, if
\begin_inset Formula $M$
\end_inset
is a valid data type, then it becomes the data-type used.
\end_layout
\begin_layout Description
vander
\begin_inset LatexCommand index
name "vander"
\end_inset
(
\begin_inset Formula $x$
\end_inset
,
\begin_inset Formula $N$
\end_inset
=None)
\end_layout
\begin_layout Description
\InsetSpace ~
The Vandermonde matrix of vector,
\begin_inset Formula $x$
\end_inset
.
The
\begin_inset Formula $i^{\textrm{th}}$
\end_inset
column of the return matrix is the
\begin_inset Formula $m_{i}^{\textrm{th}}$
\end_inset
power of
\begin_inset Formula $x$
\end_inset
where
\begin_inset Formula $m_{i}=N-i-1$
\end_inset
.
If
\begin_inset Formula $N$
\end_inset
is None, it defaults to the length of
\begin_inset Formula $x$
\end_inset
.
\end_layout
\begin_layout MyCode
>>> vander([1,2,3,4,5],3)
\newline
array([[ 1, 1, 1],
\newline
[ 4, 2, 1],
\newline
[ 9, 3, 1],
\newline
[16, 4, 1],
\newline
[25, 5, 1]])
\end_layout
\begin_layout Description
diag
\begin_inset LatexCommand index
name "diag"
\end_inset
(
\begin_inset Formula $v$
\end_inset
,
\begin_inset Formula $k$
\end_inset
=0)
\end_layout
\begin_layout Description
\InsetSpace ~
Return the
\begin_inset Formula $k^{\textrm{th}}$
\end_inset
diagonal if
\begin_inset Formula $v$
\end_inset
is a 2-d array, or returns an array with
\begin_inset Formula $v$
\end_inset
as the
\begin_inset Formula $k^{\textrm{th}}$
\end_inset
diagonal if
\begin_inset Formula $v$
\end_inset
is a 1-d array.
\end_layout
\begin_layout MyCode
>>> diag(arange(12).reshape(4,3),k=1)
\newline
array([1, 5])
\newline
>>> diag([1,4,5,7],k=-1)
\newline
array([
[0, 0, 0, 0, 0],
\newline
[1, 0, 0, 0, 0],
\newline
[0, 4, 0, 0, 0],
\newline
[0,
0, 5, 0, 0],
\newline
[0, 0, 0, 7, 0]])
\end_layout
\begin_layout Description
diagflat
\begin_inset LatexCommand index
name "diagflat"
\end_inset
(
\begin_inset Formula $v$
\end_inset
,
\begin_inset Formula $k$
\end_inset
=0)
\end_layout
\begin_layout Description
\InsetSpace ~
Return a 2-d array (of the same class as
\begin_inset Formula $v$
\end_inset
) by placing a flattened version of
\begin_inset Formula $v$
\end_inset
along the
\begin_inset Formula $k^{\textrm{th}}$
\end_inset
diagonal.
This differs from diag in that it only creates 2-d arrays and will work
with any object that can be converted to an array (returning that object
if it also defines an __array_wrap__ method).
\end_layout
\begin_layout Description
fliplr
\begin_inset LatexCommand index
name "fliplr"
\end_inset
(m)
\end_layout
\begin_layout Description
\InsetSpace ~
Return the array, m, with rows preserved and columns reversed in the left-right
direction.
For m.ndim > 2, this works on the first two dimensions (equivalent to m[:,::-1])
\end_layout
\begin_layout Description
flipud
\begin_inset LatexCommand index
name "flipud"
\end_inset
(m)
\end_layout
\begin_layout Description
\InsetSpace ~
Return the array, m, with columns preserved and rows reversed in the up-down
direction.
For m.ndim > 1, this works on the first dimension (equivalent to m[::-1])
\end_layout
\begin_layout Description
rot90
\begin_inset LatexCommand index
name "rot90"
\end_inset
(m, k=1)
\end_layout
\begin_layout Description
\InsetSpace ~
Rotate the first two dimensions of an array, m, by k*90 degrees in the
counterclockwise direction.
Must have m.ndim >=2.
\end_layout
\begin_layout Description
tri
\begin_inset LatexCommand index
name "tri"
\end_inset
(
\begin_inset Formula $N$
\end_inset
,
\begin_inset Formula $M$
\end_inset
=
\begin_inset Formula $N$
\end_inset
, k=0, dtype=aint)
\end_layout
\begin_layout Description
\InsetSpace ~
Construct an
\begin_inset Formula $N\times M$
\end_inset
array where all the diagonals starting from the lower left corner up to
the
\begin_inset Formula $\textrm{k}^{\textrm{th}}$
\end_inset
diagonal are all ones.
\end_layout
\begin_layout Description
triu
\begin_inset LatexCommand index
name "triu"
\end_inset
(m, k=0)
\end_layout
\begin_layout Description
\InsetSpace ~
Return a upper-triangular 2-d array from m with all the elements below
the
\begin_inset Formula $\textrm{k}^{\textrm{th}}$
\end_inset
diagonal set to 0.
\end_layout
\begin_layout Description
tril
\begin_inset LatexCommand index
name "tril"
\end_inset
(m, k=0)
\end_layout
\begin_layout Description
\InsetSpace ~
Return a lower-triangular 2-d array from m with all the elements above
the
\begin_inset Formula $\textrm{k}^{\textrm{th}}$
\end_inset
diagonal set to 0.
\end_layout
\begin_layout Description
mat
\begin_inset LatexCommand index
name "mat"
\end_inset
(data, dtype=None)
\end_layout
\begin_layout Description
\InsetSpace ~
Construct a matrix from data.
Alias for numpy.asmatrix.
The calling syntax is the same as that function.
Note that data can be a string in which case the routine uses spaces and
semi-colons to construct the matrix:
\end_layout
\begin_layout MyCode
>>> mat('1 3 4; 5 6 9')
\newline
matrix([[1, 3, 4],
\newline
[5, 6, 9]])
\end_layout
\begin_layout Description
bmat
\begin_inset LatexCommand index
name "bmat"
\end_inset
(obj, ldict=None, gdict=None)
\end_layout
\begin_layout Description
\InsetSpace ~
Build a matrix from sub-blocks.
This is similar to mat, except the items in the nested-sequence, or string,
should be appropriately shaped 2-d arrays.
If obj is a string, then ldict and gdict can be used to alter where the
names represented in the string are found (default is current local and
global namespace).
\end_layout
\begin_layout MyCode
>>> A=mat('1 2; 3 4'); B=mat('5 6; 7 8')
\newline
>>> bmat('A, B; B, A')
\newline
matrix([[1,
2, 5, 6],
\newline
[3, 4, 7, 8],
\newline
[5, 6, 1, 2],
\newline
[7, 8, 3, 4]])
\end_layout
\begin_layout Section
More data type functions
\end_layout
\begin_layout Description
issubclass_
\begin_inset LatexCommand index
name "issubclass\\_"
\end_inset
(arg1, arg2)
\end_layout
\begin_layout Description
\InsetSpace ~
Returns True if arg1 is a sub-class of arg2, otherwise returns False.
Similar to the built-in issubclass except it does not raise an error if
arg1 or arg2 are not types.
\end_layout
\begin_layout Description
issubdtype
\begin_inset LatexCommand index
name "issubdtype"
\end_inset
(arg1, arg2)
\end_layout
\begin_layout Description
\InsetSpace ~
Returns True if the type-object of the data-type represented by arg1 is
a sub class of the type-object of the data-type represented by arg2.
\end_layout
\begin_layout Description
iscomplexobj
\begin_inset LatexCommand index
name "iscomplexobj"
\end_inset
(obj)
\end_layout
\begin_layout Description
\InsetSpace ~
Return a single True or False value depending on whether or not obj would
be interpreted as an array with complex-valued data type.
\end_layout
\begin_layout Description
isrealobj
\begin_inset LatexCommand index
name "isrealobj"
\end_inset
(obj)
\end_layout
\begin_layout Description
\InsetSpace ~
Return a single True or False value depending on whether or not obj would
be interpreted as an array with real-valued data type.
\end_layout
\begin_layout Description
isscalar
\begin_inset LatexCommand index
name "isscalar"
\end_inset
(obj)
\end_layout
\begin_layout Description
\InsetSpace ~
True if obj is a scalar (an instance of an array data type, or a standard
Python scalar type).
There is also a sequence of called ScalarType defined in NumPy, so that
this can also be tested as type(obj) in numpy.ScalarType.
\end_layout
\begin_layout Description
nan_to_num
\begin_inset LatexCommand index
name "nan\\_to\\_num"
\end_inset
(arr)
\end_layout
\begin_layout Description
\InsetSpace ~
Returns an array with non-finite numbers changed to finite numbers.
The mapping converts
\family typewriter
nan
\family default
to 0,
\family typewriter
inf
\family default
to the maximum value for the data type and
\family typewriter
-inf
\family default
to the minimum value for the data type.
\end_layout
\begin_layout Description
real_if_close
\begin_inset LatexCommand index
name "real\\_if\\_close"
\end_inset
(arr, tol=100)
\end_layout
\begin_layout Description
\InsetSpace ~
Return a real arr if arr is complex with imaginary parts less than some
tolerance.
If tol > 1, then it represents a multiplicative factor on the value of
epsilon for the data type of arr.
\end_layout
\begin_layout Description
cast
\begin_inset LatexCommand index
name "cast"
\end_inset
[dtype_or_alias] (obj)
\end_layout
\begin_layout Description
\InsetSpace ~
Cast obj to an array of the given type.
This is equivalent to array(obj, copy=0).astype(dtype_or_alias).
When one type is cast to another in this fashion, a very low-level operation
takes place.
Typically, you get what your C-compiler produces for the cast, but notice
that in the case of casting to a bool type, the value becomes either a
0 or a 1.
\end_layout
\begin_layout MyCode
>>> cast[bool]([1,2,0,4,0]).astype(int)
\newline
array([1, 1, 0, 1, 0])
\end_layout
\begin_layout Description
asfarray
\begin_inset LatexCommand index
name "asfarray"
\end_inset
(a, dtype=float)
\end_layout
\begin_layout Description
\InsetSpace ~
Return an array of inexact data type (floating or complexfloating).
\end_layout
\begin_layout Description
mintypecode
\begin_inset LatexCommand index
name "mintypecode"
\end_inset
(typechars, typeset='GDFgdf', default='d')
\end_layout
\begin_layout Description
\InsetSpace ~
Return a minimum data type character from typeset that handles all given
typechars.
The returned type character must correspond to the data type of the smallest
size such that an array of the returned type can handle the data from an
array of type t for each t in typechars.
If the typechars does not intersect with the typeset, then default is returned.
If an element of typechars is not a string, then t=asarray(t).dtypechar
is applied.
\end_layout
\begin_layout Description
finfo
\begin_inset LatexCommand index
name "finfo"
\end_inset
(dtype)
\end_layout
\begin_layout Description
\InsetSpace ~
This class allows exploration of the details of how a floating point number
is represented in the computer.
It can be instantiated by an inexact data type object (or an alias for
one).
Complex-valued data types are acceptable and are equivalent to their real-value
d counterparts.
The attributes of the class are
\end_layout
\begin_deeper
\begin_layout Description
nmant The number of bits in the floating point mantissa, or fraction.
\end_layout
\begin_layout Description
nexp The number of bits in the floating point exponent
\end_layout
\begin_layout Description
machep Exponent of the smallest (most negative) power of 2 that when added
to 1.0 gives something different than 1.0.
\end_layout
\begin_layout Description
eps Floating point precision: 2**machep.
\end_layout
\begin_layout Description
precision Number of decimal digits of precision: int(-log10(eps))
\end_layout
\begin_layout Description
resolution 10**(-precision)
\end_layout
\begin_layout Description
negep Exponent of the smallest power of 2 that, subtracted from 1.0, gives
something different than 1.0.
\end_layout
\begin_layout Description
epsneg Floating point precision: 2**negep.
\end_layout
\begin_layout Description
minexp Smallest (most negative) power of 2 producing
\begin_inset Quotes eld
\end_inset
normal
\begin_inset Quotes erd
\end_inset
numbers (no leading zeros in the mantissa).
\end_layout
\begin_layout Description
tiny The smallest (in magnitude) usable floating point number equal to 2**minexp.
\end_layout
\begin_layout Description
maxexp Smallest (positive) power of 2 that causes overflow.
\end_layout
\begin_layout Description
max The largest usable floating value: (1-epsneg)* (2**maxep)
\end_layout
\begin_layout Description
min The most negative usable floating value: -max
\end_layout
\end_deeper
\begin_layout Description
\InsetSpace ~
The most useful attributes are probably eps, max, min, and tiny.
\end_layout
\begin_layout Section
Functions that behave like ufuncs
\end_layout
\begin_layout Standard
These functions are Python functions built on top of universal functions
(ufuncs) and also take optional output arguments.
They broadcast like ufuncs but do not have ufunc attributes.
\end_layout
\begin_layout Description
fix
\begin_inset LatexCommand index
name "fix"
\end_inset
(x, y=None)
\end_layout
\begin_layout Description
\InsetSpace ~
Round x to the nearest integer towards zero.
\end_layout
\begin_layout Description
isneginf
\begin_inset LatexCommand index
name "isneginf"
\end_inset
(x, y=None)
\end_layout
\begin_layout Description
\InsetSpace ~
True if
\begin_inset Formula $x=-\infty$
\end_inset
.
Should be the same as
\family typewriter
x==NumPy.NINF
\family default
.
\end_layout
\begin_layout Description
isposinf
\begin_inset LatexCommand index
name "isposinf"
\end_inset
(x, y=None)
\end_layout
\begin_layout Description
\InsetSpace ~
True if
\begin_inset Formula $x=+\infty.$
\end_inset
Should be the same as
\family typewriter
x==NumPy.PINF
\family default
.
\end_layout
\begin_layout Description
log2
\begin_inset LatexCommand index
name "log2"
\end_inset
(x, y=None)
\end_layout
\begin_layout Description
\InsetSpace ~
Compute the logarithm to the base 2 of
\begin_inset Formula $x.$
\end_inset
An optional output array may be provided.
\end_layout
\begin_layout Section
Miscellaneous Functions
\end_layout
\begin_layout Standard
Some miscellaneous functions are available in NumPy which are included largely
for compatibility with MLab of the old Numeric package.
One notable difference, however, is that due to a separate implementation
of the modified Bessel function, the kaiser window is available without
needing a separate library.
\end_layout
\begin_layout Description
sinc
\begin_inset LatexCommand index
name "sinc"
\end_inset
(
\begin_inset Formula $x$
\end_inset
)
\end_layout
\begin_layout Description
\InsetSpace ~
Compute the sinc function for
\begin_inset Formula $x$
\end_inset
which can be a scalar or array.
The sinc is defined as
\begin_inset Formula $y=\textrm{sinc}\left(x\right)=\frac{\sin\left(\pi x\right)}{\pi x}$
\end_inset
with the caveat that the limiting value (1.0) of the ratio is taken for
\begin_inset Formula $x=0.$
\end_inset
\end_layout
\begin_layout Description
i0
\begin_inset LatexCommand index
name "i0"
\end_inset
(
\begin_inset Formula $x$
\end_inset
)
\end_layout
\begin_layout Description
\InsetSpace ~
Modified Bessel function of the first kind of order 0.
Needed to compute the kaiser window.
The modified Bessel function is defined as
\begin_inset Formula \[
I_{0}\left(x\right)=\frac{1}{\pi}\int_{0}^{\pi}e^{x\cos\theta}d\theta=\sum_{k=0}^{\infty}\frac{x^{2k}}{4^{k}\left(k!\right)^{2}}.\]
\end_inset
\end_layout
\begin_layout Description
blackman
\begin_inset LatexCommand index
name "blackman"
\end_inset
(
\begin_inset Formula $M$
\end_inset
)
\end_layout
\begin_layout Description
\InsetSpace ~
Construct an
\begin_inset Formula $M$
\end_inset
-point Blackman smoothing window which is sequence of length
\begin_inset Formula $M$
\end_inset
with values given for
\begin_inset Formula $n=0\ldots M-1$
\end_inset
by
\begin_inset Formula \[
w\left[n\right]=0.42-0.5\cos\left(2\pi\frac{n}{M-1}\right)+0.08\cos\left(4\pi\frac{n}{M-1}\right).\]
\end_inset
\end_layout
\begin_layout Description
bartlett
\begin_inset LatexCommand index
name "bartlett"
\end_inset
(
\begin_inset Formula $M$
\end_inset
)
\end_layout
\begin_layout Description
\InsetSpace ~
Construct an
\begin_inset Formula $M$
\end_inset
-point Bartlett (triangular) smoothing window as
\begin_inset Formula \[
w\left[n\right]=\left\{ \begin{array}{cc}
2\frac{n}{M-1} & 0\leq n\leq\frac{M-1}{2},\\
2-2\frac{n}{M-1} & \frac{M-1}{2}50,\\
0.5842\left(\alpha-21\right)^{0.4}+0.07886\left(\alpha-21\right) & 21\leq\alpha\leq50,\\
0 & \alpha<21.\end{array}\right.\]
\end_inset
The length
\begin_inset Formula $M$
\end_inset
of the window determines the transition width.
To obtain a transition width of
\begin_inset Formula $\Delta\omega$
\end_inset
rad/s the window-length must be at least:
\begin_inset Formula \[
M=\frac{\alpha-8}{2.285\Delta\omega}+1.\]
\end_inset
\end_layout
\begin_layout Section
Utility functions
\end_layout
\begin_layout Description
set_numeric_ops
\begin_inset LatexCommand index
name "set\\_numeric\\_ops"
\end_inset
(=func1, =func2, ...)
\end_layout
\begin_layout Description
\InsetSpace ~
This function can be used to alter the operations used for internal array
calculations and array special methods.
Replaceable operations (and possible entries for ) are add, subtract,
multiply, divide, remainder, power, sqrt, negative, absolute, invert, left_shif
t, right_shift, bitwise_and, bitwise_or, less, less_equal, equal, not_equal,
greater, greater_equal, floor_divide, true_divide, logical_or, logical_and,
floor, ceil, maximum, and minimum.
The example code below changes, then restores, the old Numeric behavior
of remainder (which was changed because it was not consistent with Python).
\end_layout
\begin_layout MyCode
>>> a = array([-3.,-2,-1,0,1,2,3])
\newline
>>> print a % -2.1
\newline
[-0.9 -2.
-1.
0.
-1.1 -0.1 -1.2]
\newline
>>> oldops = set_numeric_ops(remainder=fmod)
\newline
>>> print a %
-2.1
\newline
[-0.9 -2.
-1.
0.
1.
2.
0.9]
\newline
>>> newops = set_numeric_ops(**oldops)
\newline
>>> print a % -2.1
\newline
[-0.9 -2.
-1.
0.
-1.1 -0.1 -1.2]
\newline
>>> print 3 % -2.1 # comparison
\newline
-1.2
\end_layout
\begin_layout Description
get_include
\begin_inset LatexCommand index
name "get\\_include"
\end_inset
()
\end_layout
\begin_layout Description
\InsetSpace ~
Return the directory that contains the numpy include files.
The numpy.distutils automatically includes this directory in building extensions.
\end_layout
\begin_layout Description
get_numarray_include
\begin_inset LatexCommand index
name "get\\_numarray\\_include"
\end_inset
(type=None)
\end_layout
\begin_layout Description
\InsetSpace ~
Return the directory that contains the numarray compatible C-API include
files.
If type is not None, then return a list containing both the numarray compatible
C-API include files and the numpy include files.
The latter form is only needed when building an extension without the use
of numpy.distutils.
\end_layout
\begin_layout Description
deprecate
\begin_inset LatexCommand index
name "deprecate"
\end_inset
(func, oldname, newname)
\end_layout
\begin_layout Description
\InsetSpace ~
Return a deprecated function named 'oldname' that has been replaced by
'newname'.
This new deprecated function issues a warning before calling the old function.
The name and docs of the function are also updated to be oldname instead
of the name that func has.
Example usage.
If you want to deprecate the function named 'old' in favor of a new function
named 'new' which has the same calling conention then this could be done
with the assignment
\end_layout
\begin_deeper
\begin_layout LyX-Code
old = deprecate(new, 'old', 'new')
\end_layout
\end_deeper
\begin_layout Chapter
Scalar objects
\end_layout
\begin_layout Standard
\begin_inset LatexCommand label
name "cha:Scalar-objects"
\end_inset
\end_layout
\begin_layout Quotation
Never worry about numbers.
Help one person at a time, and always start with the person nearest you.
\end_layout
\begin_layout Right Address
---
\emph on
Mother Teresa
\end_layout
\begin_layout Quotation
A great many people think they are thinking when they are merely rearranging
their prejudices.
\end_layout
\begin_layout Right Address
---
\emph on
William James
\end_layout
\begin_layout Standard
One
\begin_inset LatexCommand index
name "array scalars|("
\end_inset
important new feature of NumPy is the addition of a new scalar object for
each of the 21 different data types that an array can have.
Do not confuse these scalar objects with the data-type objects.
There is one data-type object.
It contains a
\family typewriter
.type
\family default
attribute which points to the Python type that each element of the array
will be returned as
\begin_inset Foot
status open
\begin_layout Standard
with the exception of object data-types which return the underlying object
and not a
\begin_inset Quotes eld
\end_inset
scalar
\begin_inset Quotes erd
\end_inset
type.
\end_layout
\end_inset
.
The built-in data-types point have .
\family typewriter
type
\family default
attributes that point to these scalar objects.
Five (or six) of these new scalar objects are essentially equivalent to
fundamental Python types and therefore inherit from them as well as from
the generic array scalar type.
The bool_ data type is very similar to the Python BooleanType but does
not inherit from it because Python's BooleanType does not allow itself
to be inherited from, and on the C-level the size of the actual bool_ data
is not the same as a Python Boolean scalar.
Table
\begin_inset LatexCommand ref
reference "cap:Array-scalar-types"
\end_inset
shows which array scalars inherit from basic Python types.
\end_layout
\begin_layout Standard
\begin_inset Float table
wide false
sideways false
status open
\begin_layout Standard
\begin_inset Caption
\begin_layout Standard
\begin_inset LatexCommand label
name "cap:Array-scalar-types"
\end_inset
Array scalar types that inherit from basic Python types.
The intc array data type might also inherit from the IntType if it has
the same number of bits as the int_ array data type on your platform.
\end_layout
\end_inset
\end_layout
\begin_layout Standard
\align center
\begin_inset Tabular
\begin_inset Text
\begin_layout Standard
array data type
\end_layout
\end_inset
|
\begin_inset Text
\begin_layout Standard
Python type
\end_layout
\end_inset
|
\begin_inset Text
\begin_layout Standard
int_
\end_layout
\end_inset
|
\begin_inset Text
\begin_layout Standard
IntType
\end_layout
\end_inset
|
\begin_inset Text
\begin_layout Standard
float_
\end_layout
\end_inset
|
\begin_inset Text
\begin_layout Standard
FloatType
\end_layout
\end_inset
|
\begin_inset Text
\begin_layout Standard
complex_
\end_layout
\end_inset
|
\begin_inset Text
\begin_layout Standard
ComplexType
\end_layout
\end_inset
|
\begin_inset Text
\begin_layout Standard
str_
\end_layout
\end_inset
|
\begin_inset Text
\begin_layout Standard
StringType
\end_layout
\end_inset
|
\begin_inset Text
\begin_layout Standard
unicode_
\end_layout
\end_inset
|
\begin_inset Text
\begin_layout Standard
UnicodeType
\end_layout
\end_inset
|
\end_inset
\end_layout
\end_inset
\end_layout
\begin_layout Standard
The array scalars have the same attributes and methods as arrays and live
in a hierarchy of scalar types so they can be easily classified based on
their type objects.
However, because array scalars are immutable, and attributes change intrinsic
properties of the object, the
\series bold
array scalar attributes are not settable
\series default
.
\end_layout
\begin_layout Standard
Array scalars can be detected using the hierarchy of data types.
For example,
\family typewriter
isinstance(val, generic)
\family default
will return True if val is an array scalar object.
Alternatively, what kind of array scalar is present can be determined using
other members of the data type hierarchy.
Thus, for example
\family typewriter
isinstance(val, complexfloating)
\family default
will return True if val is a complex valued type, while
\family typewriter
isinstance(val, flexible)
\family default
will return true if val is one of the flexible itemsize array types (string,
unicode, void).
\end_layout
\begin_layout Warning
The bool_ type is not a subclass of the int_ type (the bool_ type is not
even a number type).
This is different than Python's default implementation of bool as a sub-class
of int.
\end_layout
\begin_layout Section
Attributes of array scalars
\end_layout
\begin_layout Standard
The array scalar objects have an
\family typewriter
__array_priority__
\family default
of NPY_SCALAR_PRIORITY (-1,000,000.0).
They also do not (yet) have a ctypes attribute.
Otherwise, they share the same attributes as arrays:
\end_layout
\begin_layout Description
flags
\end_layout
\begin_layout Description
\InsetSpace ~
Returns True for CONTIGUOUS, OWNDATA, FORTRAN, and ALIGNED.
Always returns False for WRITEABLE, and UPDATEIFCOPY.
\end_layout
\begin_layout Description
shape
\end_layout
\begin_layout Description
\InsetSpace ~
Returns ().
\end_layout
\begin_layout Description
strides
\end_layout
\begin_layout Description
\InsetSpace ~
Returns ().
\end_layout
\begin_layout Description
ndim
\end_layout
\begin_layout Description
\InsetSpace ~
Returns 0.
\end_layout
\begin_layout Description
data
\end_layout
\begin_layout Description
\InsetSpace ~
A read-only buffer object of size self.itemsize,
\end_layout
\begin_layout Description
size
\end_layout
\begin_layout Description
\InsetSpace ~
Return 1.
\end_layout
\begin_layout Description
itemsize
\end_layout
\begin_layout Description
\InsetSpace ~
The number of bytes this scalar requires.
\end_layout
\begin_layout Description
base
\end_layout
\begin_layout Description
\InsetSpace ~
Returns None.
\end_layout
\begin_layout Description
dtype
\end_layout
\begin_layout Description
\InsetSpace ~
Returns data type descriptor corresponding to this array scalar.
\end_layout
\begin_layout Description
real
\end_layout
\begin_layout Description
\InsetSpace ~
The real part of the scalar.
\end_layout
\begin_layout Description
imag
\end_layout
\begin_layout Description
\InsetSpace ~
The imaginary part of the scalar (or 0 if this is real).
\end_layout
\begin_layout Description
flat
\end_layout
\begin_layout Description
\InsetSpace ~
Return a 1-d iterator object (of size 1).
\end_layout
\begin_layout Description
T
\end_layout
\begin_layout Description
\InsetSpace ~
Return a reference to self.
\end_layout
\begin_layout Description
__array_interface__
\end_layout
\begin_layout Description
\InsetSpace ~
The Python-side to the array interface.
\end_layout
\begin_layout Description
__array_struct__
\end_layout
\begin_layout Description
\InsetSpace ~
The C-side to the array interface
\end_layout
\begin_layout Description
__array_priority__
\end_layout
\begin_layout Description
\InsetSpace ~
-100.0 (very low-priority).
\end_layout
\begin_layout Description
__array_wrap__ (obj)
\end_layout
\begin_layout Description
\InsetSpace ~
Returns an array scalar from an array
\end_layout
\begin_layout Section
Methods of array scalars
\end_layout
\begin_layout Standard
Array scalars have exactly the same methods as arrays.
The default behavior of these methods is to internally convert the scalar
to an equivalent 0-dimensional array and to call the corresponding array
method.
The exceptions to these rules are given below.
In addition, math operations on array scalars are defined so that the same
hardware flags are set and used to interpret the results as for ufunc.
Therefore the error state used for ufuncs also carries over to the math
on array scalars.
\end_layout
\begin_layout Description
__new__ (obj)
\end_layout
\begin_layout Description
\InsetSpace ~
The default behavior is to return a new array or array scalar by calling
array(obj) with the corresponding data type.
There are two situations when this default behavior is delayed until another
approach is tried.
First, when the array scalar type inherits from a Python type, then the
Python types new method is called first and the default method is called
only if that approach fails.
The second situation is for the
\family typewriter
void
\family default
data type where a single integer-like argument will cause a void scalar
of that size to be created and initialized to 0.
\end_layout
\begin_layout Description
\InsetSpace ~
Notice that because array(obj) is called for new, if obj is a nested sequence,
then the return object could actually be an
\family typewriter
ndarray
\family default
.
Thus, arrays of the correct type can also be created by calling the array
data type name directly:
\end_layout
\begin_layout MyCode
>>> uint32([[5,6,7,8],[1,2,3,4]])
\newline
array([[5, 6, 7, 8],
\newline
[1, 2, 3, 4]],
dtype=uint32)
\end_layout
\begin_layout Description
__array__ ()
\end_layout
\begin_layout Description
\InsetSpace ~
Returns a 0-dimensional array of the given data type, or of type(self)
if argument is None.
\end_layout
\begin_layout Description
__array_wrap__ (array)
\end_layout
\begin_layout Description
\InsetSpace ~
Returns a scalar array object from the first-element of the array.
\end_layout
\begin_layout Description
__squeeze__ ()
\end_layout
\begin_layout Description
\InsetSpace ~
Returns self.
\end_layout
\begin_layout Description
byteswap ()
\end_layout
\begin_layout Description
\InsetSpace ~
Trying to set the first (inplace) argument to True raises a ValueError.
Otherwise, this returns a new array scalar with the data byteswapped.
\end_layout
\begin_layout Description
__reduce__ ()
\end_layout
\begin_layout Description
\InsetSpace ~
This is called to pickle an array scalar.
It returns a tuple of (numpy.core.multiarray.scalar, self.dtypestr, obj or
self.tostring()) which can be used to reconstruct the scalar on unpickling.
Notice that no state is written, because the entire scalar can be constructed
from just the string.
Also, if this is an object array scalar, then the Python object being reference
d is written.
\end_layout
\begin_layout Description
__setstate__ ()
\end_layout
\begin_layout Description
\InsetSpace ~
Does nothing but return None.
\end_layout
\begin_layout Description
setflags ()
\end_layout
\begin_layout Description
\InsetSpace ~
Does nothing, as flags cannot be set for scalars
\begin_inset LatexCommand index
name "array scalars|)"
\end_inset
.
\end_layout
\begin_layout Section
Defining New Types
\end_layout
\begin_layout Standard
There are two ways to effectively define a new type of array.
One way is to simply subclass the ndarray and overwrite the methods of
interest.
This will work to a degree, but internally certain behaviors are fixed
by the data type of the array.
To fully customize the data type of an array you need to define a new data-type
for the array, and register it with NumPy.
This new type can only be defined in C.
How to define a new data type in C will be discussed in the next part of
the book.
\end_layout
\begin_layout Chapter
Data-type (
\family typewriter
dtype
\family default
) Objects
\end_layout
\begin_layout Quotation
We cannot expect that all nations will adopt like systems, for conformity
is the jailer of freedom and the enemy of growth.
\end_layout
\begin_layout Right Address
---
\emph on
John F.
Kennedy
\end_layout
\begin_layout Quotation
What information consumes is rather obvious: it consumes the attention of
its recipients.
Hence, a wealth of information creates a poverty of attention and a need
to allocate that attention efficiently among the overabundance of information
sources that might consume it.
\end_layout
\begin_layout Right Address
---
\emph on
Herbert Simon
\end_layout
\begin_layout Standard
\begin_inset LatexCommand label
name "cha:Data-descriptor-objects"
\end_inset
It
\begin_inset LatexCommand index
name "dtype|("
\end_inset
is important not to confuse the
\begin_inset Quotes eld
\end_inset
array-scalars
\begin_inset Quotes erd
\end_inset
with the
\begin_inset Quotes eld
\end_inset
data-type objects.
\begin_inset Quotes erd
\end_inset
It is true that an array-scalar can be interpreted as a data-type object
and so can be used to refer to the data-type of an array.
However, the data-type object is a separate Python object.
Every ndarray has an associated data-type object that completely defines
the data in the array (including any named fields).
For every built-in data-type object there is an associated type object
whose instances are the array-scalars.
Because of the association between each data-type object and a type-object
of the corresponding array scalar, the array-scalar type-objects can also
be thought of as data-types.
However, for the type objects of flexible array-scalars (string, unicode_,
and void), the type-objects alone are not enough to specify the full data-type
because the length is not given.
The data-type constructor,
\series bold
numpy.dtype
\series default
, converts any object that can be considered as a data-type into a data-type
object which is the actual object an ndarray looks to in order to interpret
each element of its data region.
Whenever a data-type is required in a NumPy function or method, supplying
a dtype object is always fastest.
If the object supplied is not a dtype object, then it will be converted
to one using dtype(obj).
Therefore, understanding data-type objects is the key to understanding
how data types are really represented and understood in NumPy.
\end_layout
\begin_layout Section
Attributes
\begin_inset LatexCommand index
name "dtype!attributes|("
\end_inset
\end_layout
\begin_layout Description
type
\begin_inset LatexCommand index
name "dtype!attributes!type"
\end_inset
The
\begin_inset LatexCommand index
name "The"
\end_inset
type object used to instantiate a scalar of this data-type.
\end_layout
\begin_layout Description
kind
\begin_inset LatexCommand index
name "dtype!attributes!kind"
\end_inset
A character code (one of 'biufcSUV') identifying the general kind of data.
\end_layout
\begin_layout Description
char
\begin_inset LatexCommand index
name "dtype!attributes!char"
\end_inset
A unique character code for each of the 21 different built-in types.
\end_layout
\begin_layout Description
num
\begin_inset LatexCommand index
name "dtype!attributes!num"
\end_inset
A unique number for each of the 21 different built-in types roughly ordered
from least-to-most precision.
\end_layout
\begin_layout Description
str
\begin_inset LatexCommand index
name "dtype!attributes!str"
\end_inset
The array-protocol typestring of this data-type object.
\end_layout
\begin_layout Description
name
\begin_inset LatexCommand index
name "dtype!attributes!name"
\end_inset
A bit-width name for this data-type (un-sized flexible data-type objects
are missing the width).
\end_layout
\begin_layout Description
byteorder
\begin_inset LatexCommand index
name "dtype!attributes!byteorder"
\end_inset
A character indicating the byte-order of this data-type object ('=' : native,
'<' : little-endian, '>' : big-endian, '|' : not applicable).
All built-in data-type objects have byteorder either '=' or '|'.
\end_layout
\begin_layout Description
itemsize
\begin_inset LatexCommand index
name "dtype!attributes!itemsize"
\end_inset
The element size of this data-type object.
For 18 of the 21 types this number is fixed by the data-type.
For the flexible data-types, this number can be anything.
\end_layout
\begin_layout Description
alignment
\begin_inset LatexCommand index
name "dtype!attributes!alignment"
\end_inset
The required alignment (in bytes) of this data-type according to the compiler.
More information is available in the C-API section.
\end_layout
\begin_layout Description
fields
\begin_inset LatexCommand index
name "dtype!attributes!fields"
\end_inset
A dictionary showing any named fields that have been defined for this data-type
(or None if there are no named fields).
Fields can be assigned to any built-in data-type (
\emph on
e.g.
\emph default
using the tuple input to the dtype constructor).
However, fields are most useful for (subtypes of) void data-types which
can be any size.
Fields are a convenient way to keep track of fixed-size sub-parts of the
total fixed-size array-element, or record.
A field is defined in terms of another dtype object and an offset (in bytes)
into the current record.
\end_layout
\begin_layout Description
\InsetSpace ~
The fields dictionary is indexed by keys that are the names of the fields.
Each entry in the dictionary is a tuple fully describing the field: (dtype,
offset[, title]).
If present, the optional title can actually be any object (if it is string
or unicode then it will also be a key in the fields dictionary, otherwise
it's meta-data).
Notice also, that the first two elements of the tuple can be passed directly
as arguments to the getfield and setfield attributes of an ndarray.
If field names are not specified in a constructor, they default to 'f0',
'f2', ..., 'f'.
\end_layout
\begin_layout Description
names
\begin_inset LatexCommand index
name "dtype!attributes!char"
\end_inset
An ordered list of field names.
This can be used to walk through all of the named fields in offset order.
Notice that the defined fields do not have to
\begin_inset Quotes eld
\end_inset
cover
\begin_inset Quotes erd
\end_inset
the record, but the itemsize of the container data-type object must always
be at least as large as the itemsizes of the data-type objects in the defined
fields.
This attribute is None if there are no fields.
\end_layout
\begin_layout Description
subdtype
\begin_inset LatexCommand index
name "dtype!attributes!subdtype"
\end_inset
Numarray introduced the concept of a fixed-length record having fields
that were themselves arrays of another data-type.
This is supported at a fundamental level in NumPy using this attribute
which maintains the simplicity of defining a field by another data-type
object.
It either returns None or a tuple (base dtype, shape) where shape is a
tuple showing the size of the C-contiguous array and the base dtype object
indicates the data-type in each element of the subarray.
If a field whose dtype object has this attribute is retrieved, then the
extra dimensions implied by the shape are tacked on to the end of the retrieved
array.
\end_layout
\begin_layout Description
descr
\begin_inset LatexCommand index
name "dtype!attributes!descr"
\end_inset
An array-interface-compliant full description of the data-type.
The format is that required by the 'descr' key in the __array_interface__.
\end_layout
\begin_layout Description
isbuiltin
\begin_inset LatexCommand index
name "dtype!attributes!isbuiltin"
\end_inset
A 1 if self is one of the built-in dtype objects; a 2 if self is a user-defined
dtype object; a 0, otherwise.
\end_layout
\begin_layout Description
isnative
\begin_inset LatexCommand index
name "dtype!attributes!isnative"
\end_inset
True if this data-type object has a byteorder that is native to the platform;
otherwise False.
\end_layout
\begin_layout Description
hasobject
\begin_inset LatexCommand index
name "dtype!attributes!hasobject"
\end_inset
True if self contains reference-counted objects in any of it's fields or
sub data-types.
Recall that what is actually in the ndarray memory representing the Python
object is the memory address of that object (a pointer).
Special handling may be required and this attribute is useful for distinguishin
g data-types that may contain arbitrary Python objects and data-types that
won't.
\end_layout
\begin_layout Description
flags
\begin_inset LatexCommand index
name "dtype!attributes!flags"
\end_inset
Bit-flags for the data-type describing how the data-type will be interpreted.
Bit-masks are in numpy.core.multiarray as the constants ITEM_HASOBJECT, LIST_PICK
LE, ITEM_IS_POINTER, NEEDS_INIT, NEEDS_PYAPI, USE_GETITEM, USE_SETITEM.
A full explanation of these flags is in the second part of this book.
These flags are largely useful for user-defined data-types.
\begin_inset LatexCommand index
name "dtype!attributes|)"
\end_inset
\end_layout
\begin_layout Section
Construction
\end_layout
\begin_layout Description
dtype (obj, align=0, copy=0)
\end_layout
\begin_layout Description
\InsetSpace ~
\begin_inset LatexCommand index
name "dtype!construction|("
\end_inset
Return a new data-type object from obj.
The keyword argument, align, can only be nonzero if obj is a dictionary,
or a comma-separated string.
If it is non-zero in those cases it is used to add padding as needed to
the fields to match what the compiler that compiled NumPy would do to a
similar C-struct.
The copy argument guarantees a new copy of the data-type object, otherwise,
the result may just be a reference to a built-in data-type object.
\end_layout
\begin_layout Description
\InsetSpace ~
Objects that can be converted to a data-type object are described in the
following list.
Because every object in this list can be converted to a data-type object
it can also be used whenever a
\family typewriter
dtype
\family default
is requested by a function or method in NumPy.
\end_layout
\begin_deeper
\begin_layout Description
dtype
\begin_inset LatexCommand index
name "dtype!construction!from float"
\end_inset
Returns itself.
\end_layout
\begin_layout Description
None
\begin_inset LatexCommand index
name "dtype!construction!from None"
\end_inset
Returns the default data-type descriptor object: float.
\end_layout
\begin_layout Description
type-object
\begin_inset LatexCommand index
name "dtype!construction!from type"
\end_inset
Many Python type objects can be converted to data-type objects.
\end_layout
\begin_deeper
\begin_layout Enumerate
Array-scalar types: The type-objects of the 21 built-in array scalars all
convert to an associated data-type object.
This is true for sub-classes as well.
Not all data-type information can be supplied with a type-object.
Flexible data-types with default itemsizes of 0, for example, require an
itemsize to be useful.
\end_layout
\begin_deeper
\begin_layout Description
Examples: int32, float64, uint16, complex128
\end_layout
\end_deeper
\begin_layout Enumerate
Generic types: The generic hierarchical type objects convert to corresponding
dtype objects according to the associations: (numeric, inexact, floating)
--> float; complexfloating --> cfloat; (integer, signedinteger) --> int_;
unsignedinteger --> uint; character --> string; (generic, flexible) -->
void.
\end_layout
\begin_layout Enumerate
Builtin types: Several python types are equivalent to a corresponding array
scalar when used to generate a dtype object: int --> int_; bool --> bool_;
float --> float_; complex --> cfloat; str --> string; unicode --> unicode_;
buffer --> void; (all others) --> object_.
\end_layout
\begin_deeper
\begin_layout Description
Examples: object, str, float, int
\end_layout
\end_deeper
\begin_layout Enumerate
Any type object with the dtype attribute: The attribute will be accessed
and used directly.
The attribute must return something that is convertible into a dtype object.
\end_layout
\end_deeper
\begin_layout Description
string
\begin_inset LatexCommand index
name "dtype!construction!from string"
\end_inset
Several kinds of strings can be converted.
Recognized strings can be pre-pended with '>', or '<', to specify the byteorder.
\end_layout
\begin_deeper
\begin_layout Enumerate
One-character strings: Each built-in data-type has a character code (the
updated Numeric typecodes), that uniquely identifies it.
\end_layout
\begin_deeper
\begin_layout Description
Examples: 'b', 'H', 'f', 'd', 'F', 'D', Float64, Int32, UInt16
\end_layout
\end_deeper
\begin_layout Enumerate
Array-protocol type strings: The first character specifies the kind of data
and the remaining characters specify how many bytes of data.
The supported kinds are 'b' --> Boolean, 'i' --> (signed) integer, 'u'
--> unsigned integer, 'f' --> floating-point, 'c' --> complex-floating
point, 'S', 'a' --> string, 'U' --> unicode, 'V' --> anything (void).
\end_layout
\begin_deeper
\begin_layout Description
Examples: 'i4', 'f8', 'c16', 'b1', 'S10', 'a25'
\end_layout
\end_deeper
\begin_layout Enumerate
Comma-separated field formats: numarray introduced a short-hand notation
for specifying the format of a record as a comma-separated string of basic
formats.
A basic format in this context is an optional shape specifier followed
by an array-protocol type string.
Parenthesis are required on the shape if it is greater than 1-d.
NumPy allows a modification on the format in that any string that can uniquely
identify the type can be used to specify the data-type in a field.
This data-type defines fields named 'f0', 'f2', ..., 'f' where N (>1)
is the number of comma-separated basic formats in the string.
If the optional shape specifier is provided, then the data-type for the
corresponding field contains a subdtype attribute providing the shape.
\end_layout
\begin_deeper
\begin_layout Description
Examples:
\begin_inset Quotes eld
\end_inset
i4, (2,3)f8, f4
\begin_inset Quotes erd
\end_inset
;
\begin_inset Quotes eld
\end_inset
a3, 3u8, (3,4)a10
\begin_inset Quotes erd
\end_inset
\end_layout
\end_deeper
\begin_layout Enumerate
Any string in NumPy.sctypeDict.keys():
\end_layout
\begin_deeper
\begin_layout Description
Examples: 'uint32', 'Int16', 'Uint64', 'Float64', 'Complex64'
\end_layout
\end_deeper
\end_deeper
\begin_layout Description
tuple
\begin_inset LatexCommand index
name "dtype!construction!from tuple"
\end_inset
Three kinds of tuples each of length 2 can be converted into a data-type
object:
\end_layout
\begin_deeper
\begin_layout Enumerate
(flexible dtype, itemsize): The first argument must be an object that is
converted to a flexible data-type object (one whose element size is 0),
the second argument is an integer providing the desired itemsize.
\end_layout
\begin_deeper
\begin_layout Description
Examples: (void, 10); (str, 35), ('U', 10)
\end_layout
\end_deeper
\begin_layout Enumerate
(fixed dtype, shape): The first argument is any object that can be converted
into a fixed-size data-type object.
The second argument is the desired shape of this type.
If the shape parameter is 1, then the data-type object is equivalent to
fixed dtype.
\end_layout
\begin_deeper
\begin_layout Description
Examples: (int32, (2,5)); ('S10', 1)=='S10'; ('i4, (2,3)f8, f4', (2,3))
\end_layout
\end_deeper
\begin_layout Enumerate
(base dtype, new dtype): Both arguments must be convertible to data-type
objects in this case.
The base dtype is the data-type object that the new data-type builds on.
This is how you could assign named fields to any built-in data-type object.
\end_layout
\begin_deeper
\begin_layout Description
Examples: (int32, {'real':(int16,0), 'imag':(int16,2)}); (int32, (int8,
4));
\newline
('i4', [('r','u1'),('g','u1'),('b','u1'),('a','u1')])
\end_layout
\end_deeper
\end_deeper
\begin_layout Description
list
\begin_inset LatexCommand index
name "dtype!construction!from list"
\end_inset
(array description interface): This style is more fully described at
\begin_inset LatexCommand url
name "this site"
target "http://numpy.scipy.org/array_interface.html"
\end_inset
.
It consists of a list of fields where each field is described by a tuple
of length 2 or 3.
The first element of the tuple is the field name (if this is '' then a
standard field name, 'f#', is assigned).
The field name may also be a 2-tuple of strings where the first string
is either a
\begin_inset Quotes eld
\end_inset
title
\begin_inset Quotes erd
\end_inset
(which may be any string or unicode string) or meta-data for the field
which can be any object, and the second string is the
\begin_inset Quotes eld
\end_inset
name
\begin_inset Quotes erd
\end_inset
which must be a valid Python identifier.
The second element of the tuple can be anything that can be interpreted
as a data-type.
The optional third element of the tuple contains the shape if this field
represents an array of the data-type in the second element.
This style does not accept align=1 as it is assumed that all of the memory
is accounted for by the array interface description.
See the web-page for more examples.
Note that a 3-tuple with a third argument equal to 1 is equivalent to a
2-tuple.
\end_layout
\begin_layout Description
Examples: [('big','>i4'), ('little',')
\end_layout
\begin_layout Description
\InsetSpace ~
Construct a new copy of self with its byteorder changed according to the
optional argument.
All changes are also propagated to the data-type objects of all fields
and sub-arrays.
If a byteorder of '|' (meaning ignore) is encountered it is left unchanged.
The default behavior is to swap the byteorder.
Other possible arguments are 'big' ('>'), 'little' ('<'), and 'native'
('=') which recursively forces the byteorder of self (and it's field data-type
objects and any sub-arrays) to the corresponding byteorder.
\end_layout
\begin_layout Description
__reduce__
\begin_inset LatexCommand index
name "dtype!methods!\\_\\_reduce\\_\\_"
\end_inset
()
\end_layout
\begin_layout Description
__setstate__
\begin_inset LatexCommand index
name "dtype!methods!\\_\\_setstate\\_\\_"
\end_inset
(state)
\end_layout
\begin_layout Description
\InsetSpace ~
Data-type objects can be pickled because of these two methods.
The __reduce__() method returns a 3-tuple consisting of (callable object,
args, state), where the callable object is numpy.core.multiarray.dtype and
args is (typestring, 0, 1) unless the data-type inherits from void (or
is user-defined) in which case args is (typeobj, 0, 1).
The state is an 8-tuple with (version, endian, self.subdtype, self.names,
self.fields, self.itemsize, self.alignment, self.flags).
The self.itemsize and self.alignment entries are both -1 if the data-type
object is built-in and not flexible (because they are fixed on creation).
The setstate method takes the saved state and updates the date-type
\begin_inset LatexCommand index
name "dtype!methods|)"
\end_inset
object.
\begin_inset LatexCommand index
name "dtype|)"
\end_inset
\end_layout
\begin_layout Chapter
Standard Classes
\end_layout
\begin_layout Quotation
To generalize is to be an idiot.
\end_layout
\begin_layout Right Address
---
\emph on
William Blake
\end_layout
\begin_layout Quotation
Not everything that can be counted counts, and not everything that counts
can be counted.
\end_layout
\begin_layout Right Address
---
\emph on
Albert Einstein
\end_layout
\begin_layout Standard
\begin_inset LatexCommand index
name "ndarray!subtyping|("
\end_inset
The ndarray in NumPy is a
\begin_inset Quotes eld
\end_inset
new-style
\begin_inset Quotes erd
\end_inset
Python built-in-type.
Therefore, it can be inherited from (in Python or in C) if desired.
Therefore, it can form a foundation for many useful classes.
Often whether to sub-class the array object or to simply use the core array
component as an internal part of a new class is a difficult decision, and
can be simply a matter of choice.
NumPy has several tools for simplifying how your new object interacts with
other array objects, and so the choice may not be significant in the end.
One way to simplify the question is by asking yourself if the object you
are interested can be replaced as a single array or does it really require
two or more arrays at it's core.
For example, in the standard NumPy distribution, the matrix and records
classes inherit from the ndarray, while masked arrays use two ndarrays
as objects of its internal structure.
\end_layout
\begin_layout Standard
Note that asarray(a) always returns the base-class ndarray.
If you are confident that your use of the array object can handle any subclass
of an ndarray, then asanyarray(a) can be used to allow subclasses to propagate
more cleanly through your subroutine.
In principal a subclass could redefine any aspect of the array and therefore,
under strict guidelines, asanyarray(a) would rarely be useful.
However, most subclasses of the arrayobject will not redefine certain aspects
of the array object such as the buffer interface, or the attributes of
the array.
One of important example, however, of why your subroutine may not be able
to handle an arbitrary subclass of an array is that matrices redefine the
'*' operator to be matrix-multiplication, rather than element-by-element
multiplication.
\end_layout
\begin_layout Section
Special attributes and methods recognized by NumPy
\begin_inset LatexCommand index
name "ndarray!attributes!recognized by|("
\end_inset
\end_layout
\begin_layout Description
__array_finalize__ (obj)
\end_layout
\begin_layout Description
\InsetSpace ~
This method is called whenever the system internally allocates a new array
from obj, where obj is a subclass (subtype) of the (big)ndarray.
It can be used to change attributes of self after construction (so as to
ensure a 2-d matrix for example), or to update meta-information from the
\begin_inset Quotes eld
\end_inset
parent.
\begin_inset Quotes erd
\end_inset
Subclasses inherit a default implementation of this method that does nothing.
\end_layout
\begin_layout Description
__array_wrap__ (array)
\end_layout
\begin_layout Description
\InsetSpace ~
This method should return an instance of the class from the ndarray object
passed in.
For example, this is called after every ufunc for the object with the highest
__array_priority__.
The ufunc-computed array object is passed in and whatever is returned is
passed to the user.
Subclasses inherit a default implementation of this method.
\end_layout
\begin_layout Description
__array__ (dtype )
\end_layout
\begin_layout Description
\InsetSpace ~
This method is called to obtain an ndarray object when needed.
You should always guarantee this returns an actual ndarray object.
Subclasses inherit a default implementation of this method.
\end_layout
\begin_layout Description
__array_priority__
\end_layout
\begin_layout Description
\InsetSpace ~
The value of this attribute is used to determine what type of object to
return in situations where there is more than one possibility for the Python
type of the returned object.
Subclasses inherit a default value of 1.0 for this attribute.
\begin_inset LatexCommand index
name "ndarray!attributes!recognized by|)"
\end_inset
\begin_inset LatexCommand index
name "ndarray!subtyping|)"
\end_inset
\end_layout
\begin_layout Section
Matrix Objects
\end_layout
\begin_layout Standard
\begin_inset LatexCommand index
name "matrix|("
\end_inset
Matrix objects inherit from the ndarray and therefore, they have the same
attributes and methods of ndarrays.
There are six important differences of matrix objects, however that may
lead to unexpected results when you use matrices but expect them to act
like arrays:
\end_layout
\begin_layout Enumerate
Matrix objects can be created using a string notation to allow Matlab-style
syntax where spaces separate columns and semicolons (';') separate rows.
\end_layout
\begin_layout Enumerate
Matrix objects are always two-dimensional.
This has far-reaching implications, in that m.ravel() is still two-dimensional
(with a 1 in the first dimension) and item selection returns two-dimensional
objects so that sequence behavior is fundamentally different than arrays.
\end_layout
\begin_layout Enumerate
Matrix objects over-ride multiplication to be matrix-multiplication.
\series bold
Make sure you understand this for functions that you may want to receive
matrices.
Especially in light of the fact that asanyarray(m) returns a matrix when
m is a matrix.
\end_layout
\begin_layout Enumerate
Matrix objects over-ride power to be matrix raised to a power.
The same warning about using power inside a function that uses asanyarray(...)
to get an array object holds for this fact.
\end_layout
\begin_layout Enumerate
The default __array_priority__ of matrix objects is 10.0, and therefore mixed
operations with ndarrays always produce matrices.
\end_layout
\begin_layout Enumerate
Matrices have special attributes which make calculations easier.
These are
\end_layout
\begin_deeper
\begin_layout Enumerate
.T --- return the transpose of self
\end_layout
\begin_layout Enumerate
.H --- return the conjugate transpose of self
\end_layout
\begin_layout Enumerate
.I --- return the inverse of self
\end_layout
\begin_layout Enumerate
.A --- return a view of the data of self as a 2d array (no copy is done).
\end_layout
\end_deeper
\begin_layout Warning
Matrix objects over-ride multiplication, '*', and power, '**', to be matrix-mult
iplication and matrix power, respectively.
If your subroutine can accept sub-classes and you do not convert to base-class
arrays, then you must use the ufuncs multiply and power to be sure that
you are performing the correct operation for all inputs.
\end_layout
\begin_layout Standard
The matrix class is a Python subclass of the ndarray and can be used as
a reference for how to construct your own subclass of the ndarray.
Matrices can be created from other matrices, strings, and anything else
that can be converted to an
\family typewriter
ndarray
\family default
.
The name
\begin_inset Quotes eld
\end_inset
mat
\begin_inset Quotes erd
\end_inset
is an alias for
\begin_inset Quotes eld
\end_inset
matrix
\begin_inset Quotes erd
\end_inset
in NumPy.
\end_layout
\begin_layout Description
Example\InsetSpace ~
1: Matrix creation from a string
\end_layout
\begin_layout MyCode
>>> a=mat('1 2 3; 4 5 3')
\newline
>>> print (a*a.T).I
\newline
[[ 0.2924 -0.1345]
\newline
[-0.1345 0.0819]]
\end_layout
\begin_layout Description
Example\InsetSpace ~
2: Matrix creation from nested sequence
\end_layout
\begin_layout MyCode
>>> mat([[1,5,10],[1.0,3,4j]])
\newline
matrix([[ 1.+0.j, 5.+0.j, 10.+0.j],
\newline
[
1.+0.j, 3.+0.j, 0.+4.j]])
\end_layout
\begin_layout Description
Example\InsetSpace ~
3: Matrix creation from an array
\end_layout
\begin_layout MyCode
>>> mat(random.rand(3,3)).T
\newline
matrix([[ 0.7699, 0.7922, 0.3294],
\newline
[ 0.2792,
0.0101, 0.9219],
\newline
[ 0.3398, 0.7571, 0.8197]])
\end_layout
\begin_layout Description
matrix (data, dtype=None, copy=True)
\end_layout
\begin_layout Description
\InsetSpace ~
The sequence to convert to a matrix is passed in as data.
If dtype is None, then the data-type is determined from the data.
If copy is True, then a copy of the data is made, otherwise, the same data
buffer is used.
If no buffer can be found for data, then a copy is also made.
Note: The matrix object is actually a class and so using this syntax calls
matrix.__new__(matrix, data, dtype, copy) which is what happens whenever
you
\begin_inset Quotes eld
\end_inset
call
\begin_inset Quotes erd
\end_inset
any class object as a function.
\end_layout
\begin_layout Description
mat
\end_layout
\begin_layout Description
\InsetSpace ~
Just another name for matrix.
\end_layout
\begin_layout Description
asmatrix (data, dtype=None)
\end_layout
\begin_layout Description
\InsetSpace ~
Returns the data without copying.
Equivalent to matrix(data, dtype, copy=False).
\end_layout
\begin_layout Description
bmat (obj, ldict=None, gdict=None)
\end_layout
\begin_layout Description
\InsetSpace ~
Build a matrix object from a string, nested sequence or an array.
This command lets you build up matrices from other other objects.
The ldict and gdict parameters are local and module (global) dictionaries
that are only used when obj is a string.
If they are not provided, then the local and module dictionaries present
when bmat is called are used.
\begin_inset LatexCommand index
name "matrix|)"
\end_inset
\end_layout
\begin_layout MyCode
>>> A = mat('2 2; 2 2'); B=mat('1 1; 1 1');
\newline
>>> print bmat('A B; B A')
\newline
[[2
2 1 1]
\newline
[2 2 1 1]
\newline
[1 1 2 2]
\newline
[1 1 2 2]]
\end_layout
\begin_layout Section
Memory-mapped-file arrays
\end_layout
\begin_layout Standard
\begin_inset LatexCommand index
name "memory maps|("
\end_inset
Memory-mapped files are useful for reading and/or modifying small segments
of a large file with regular layout, without reading the entire file into
memory.
A simple subclass of the ndarray uses a memory-mapped file for the data
buffer of the array.
For small files, the over-head of reading the entire file into memory is
typically not significant, however for large files using memory mapping
can save considerable resources.
\end_layout
\begin_layout Note
Memory-mapped arrays use the the Python memory-map object which (prior to
Python 2.5) does not allow files to be larger than a certain size depending
on the platform.
This size is always < 2GB even on 64-bit systems.
\end_layout
\begin_layout Standard
The class is called memmap and is available in the NumPy namespace.
The __new__ method of the class has been re-written to have the following
syntax:
\end_layout
\begin_layout Description
__new__ (cls, filename, dtype=uint8, mode='r+', offset=0, shape=None, order=0)
\end_layout
\begin_deeper
\begin_layout Description
filename The file name to be used as the array data buffer
\end_layout
\begin_layout Description
dtype A data-type object used to interpret the file contents (including
byteorder).
\end_layout
\begin_layout Description
mode The mode to open the file in.
Valid modes are 'readonly' or 'r', 'copyonwrite' or 'c', 'readwrite' or
'r+', and 'write' or 'w+'.
This mode determines the WRITEABLE flag of the returned array.
\end_layout
\begin_layout Description
offset An offset into the file to start the array data.
\end_layout
\begin_layout Description
shape The desired shape of the array.
If this is None, then the returned array will be 1-d with the number of
elements determined by the file size and data type.
\end_layout
\begin_layout Description
order Either 'C' or 'Fortran' to indicate the order that an N-D array should
be interpreted.
This only has an effect if the shape is greater than 2-D.
\end_layout
\end_deeper
\begin_layout Standard
Memory-mapped-file arrays have one additional method (besides those they
inherit from the ndarray): self.
\series bold
flush
\series default
() which can be called manually by the user to ensure that any changes to
the array actually get written to disk. This also occurs on deleting
the memmap object
\end_layout
\begin_layout Description
Example:
\end_layout
\begin_layout MyCode
>>> a = memmap('newfile.dat', dtype=float, mode='w+', shape=1000)
\newline
>>> a[10]
= 10.0
\newline
>>> a[30] = 30.0
\newline
>>> del a
\newline
>>> b = fromfile('newfile.dat', dtype=float)
\newline
>>>
print b[10], b[30]
\newline
10.0 30.0
\newline
>>> a = memmap('newfile.dat', dtype=float)
\newline
>>> print
a[10], a[30]
\newline
10.0 30.0
\end_layout
\begin_layout Section
Character arrays (numpy.char)
\end_layout
\begin_layout Standard
\begin_inset LatexCommand index
name "character arrays|("
\end_inset
These are enhanced arrays of either string type or unicode_ type.
These arrays inherit from the ndarray, but specially-define the operations
+, *, and % on a (broadcasting) element-by-element basis.
These operations are not available on the standard ndarray of character
type.
In addition, the chararray has all of the standard string (and unicode)
methods, executing them on an element-by-element basis.
Perhaps the easiest way to create a chararray is to use self.view(chararray)
where self is an ndarray of string or unicode data-type.
However, a chararray can also be created using the numpy.chararray.__new__
method.
\end_layout
\begin_layout Description
__new__ (shape, itemsize, unicode=False, buffer=None, offset=0, strides=None,
order=None)
\end_layout
\begin_layout Description
\InsetSpace ~
Create a new character array of string or unicode type and itemsize characters.
Create the array using buffer (with offset and strides) if it is not None.
If buffer is None, then construct a new array with strides in Fortran order
if len(shape) >=2 and order is 'Fortran' (otherwise the strides will be
in 'C' order).
\end_layout
\begin_layout Description
char.array (obj, itemsize=None, copy=True, unicode=False, order=None)
\end_layout
\begin_layout Description
\InsetSpace ~
Create a chararray from the nested sequence obj.
If obj is an ndarray of data-type unicode_ or string, then its data is
wrapped by the chararray object and converted to the desired type (string
or unicode).
\end_layout
\begin_layout Standard
Another difference with the standard ndarray of string data-type is that
the chararray inherits the feature introduced by Numarray that white-space
at the end of any element in the array will be ignored on item retrieval
and comparison operations.
\begin_inset LatexCommand index
name "character arrays|)"
\end_inset
\end_layout
\begin_layout Section
Record Arrays (numpy.rec)
\end_layout
\begin_layout Standard
\begin_inset LatexCommand index
name "record arrays|("
\end_inset
NumPy provides a powerful data-type object that allows any ndarray to hold
(arbitrarily nested) record-like items with named-field access to the sub-types.
This is possible without any special record-array sub-class.
Consider the example where each item in the array is a simple record of
name, age, and weight.
You could specify a data-type for an array of such records using the following
data-type object:
\end_layout
\begin_layout MyCode
>>> desc = dtype({'names': ['name', 'age', 'weight'], 'formats': ['S30',
'i2', 'f4']})
\newline
>>> a = array([('Bill',31,260.0),('Fred', 15, 145.0)],dtype=desc)
\newline
>>>
print a[0]
\newline
('Bill', 31, 260.0)
\newline
>>> print a['name']
\newline
['Bill' 'Fred']
\newline
>>> print
a['age']
\newline
[31 15]
\newline
>>> print a['weight']
\newline
[ 260.
145.]
\newline
>>> print a[0]['name'], a[0]['age'], a[0]['weight']
\newline
Bill 31 260.0
\newline
>>>
print len(a[0])
\newline
3
\end_layout
\begin_layout Standard
This example shows how a general array can be assigned named fields and
how these fields can be accessed.
In this case the a[0] object is an array-scalar of type void.
The void array-scalars are unique in that they contain references to (rather
than copies of) the underlying data whenever fields are defined.
Therefore, the record data can be modified in place:
\end_layout
\begin_layout MyCode
>>> a[0]['name'] = 'George'; print a
\newline
[('George', 31, 260.0) ('Fred', 15, 145.0)]
\end_layout
\begin_layout Standard
The recarray subclass and its accompanying record item add the ability to
access named fields through attribute lookup.
A quick way to get a record array is to use the view method of the ndarray.
\end_layout
\begin_layout MyCode
>>> r = a.view(recarray)
\newline
>>> print r.name
\newline
['George' 'Fred']
\end_layout
\begin_layout Standard
The numpy.core.records module (aliased to nump.rec when numpy is imported)
contains additional convenience functions for constructing record arrays.
All of the following constructors have two different mechanisms for specifying
the data-type.
Either the dtype= argument can be specified or the argument formats= can
be specified along with an optional set of four additional keyword arguments
(names=, titles=, aligned= and byteorder=).
In some cases neither dtype= nor formats= is required as the data-type
can be inferred from the object passed in as the first argument.
\end_layout
\begin_layout Standard
The five argument method for specifying a data-type constructs a data-type
object internally.
The comma-separated formats string is used to specify the fields.
The names (and optional titles) of the fields can be specified by a comma-separ
ated string of names (or titles).
The aligned flag determines whether the fields are packed (False) or padded
(True) according to the platform compiler rules.
The byteorder argument allows specification of the byte-order for all of
the fields at once (they can also be specified individually in the formats
string).
The default byte-order is native to the platform.
\end_layout
\begin_layout Description
array (obj, dtype=None, shape=None, offset=0, strides=None, formats=None,
names=None, titles=None, aligned=False, byteorder=None, copy=True)
\end_layout
\begin_layout Description
\InsetSpace ~
A general-purpose record array constructor that is a front-end to the other
constructors If obj is None, then call the
\series bold
recarray
\series default
constructor.
If obj is a string, then call the
\series bold
fromstring
\series default
constructor.
If obj is a list or a tuple then if the first object is an ndarray, then
call
\series bold
fromarrays
\series default
, otherwise call
\series bold
fromrecords
\series default
.
If obj is a recarray, then make a copy of the data in recarray (if copy
is True) and use the new formats, names, and titles.
If obj is a file then call
\series bold
fromfile
\series default
.
Finally, if obj is an ndarray, then return obj.view(recarray) and make a
copy of the data if copy is True.
Otherwise, call the __array_interface__ attribute and try to convert using
the information returned from that object.
Either dtype or the formats argument must be given if obj is None, a string,
or a file, and if obj is None so the recarray constructor will be called,
then shape must be given as well.
\end_layout
\begin_layout Description
fromarrays (array_list, dtype=None, shape=None, formats=None, names=None,
titles=None, aligned=False, byteorder=None)
\end_layout
\begin_layout Description
\InsetSpace ~
Create a record array from a (flat) list of ndarrays.
The data from the arrays will be copied into the fields.
If formats is None and dtype is None, then the formats will be determined
from the arrays.
The names and titles arguments can be a list, tuple or a (comma-separated)
string specifying the names and/or titles to use for the fields.
If aligned is True, then the structure will be padded according to the
rules of the compiler that NumPy was compiled with.
\end_layout
\begin_layout MyCode
>>> x1 = array([21,32,14])
\newline
>>> x2 = array(['my','first','name'])
\newline
>>> x3 =
array([3.1, 4.5, 6.2])
\newline
>>> r = rec.fromarrays([x1,x2,x3], names='id, word, number')
\newline
>
>> print r[1]
\newline
(32, 'first', 4.5)
\newline
>>> r.number
\newline
array([ 3.1, 4.5, 6.2])
\newline
>>> r.word
\newline
chararra
y(['my', 'first', 'name'],
\newline
dtype='|S5')
\end_layout
\begin_layout Description
fromrecords (rec_list, dtype=None, shape=None, formats=None, names=None,
titles=None, aligned=False, byteorder=None)
\end_layout
\begin_layout Description
\InsetSpace ~
Construct a record array from a (nested) sequence of tuples that define
the records.
If formats are not given, they are deduced from the records, but this is
slower.
The field names and field titles can be specified.
If aligned is non-zero, then the record array is padded so that fields
are aligned as the platform compiler would do if the fields represented
a C-struct.
\end_layout
\begin_layout MyCode
>>> recs = [('Bill', 31, 260.0), ('Fred', 15, 145.0)]
\newline
>>> r = rec.fromrecords(recs,
formats='S30,i2,f4', names='name, age, weight')
\newline
>>> print r.name
\newline
['Bill' 'Fred']
\newline
>>
> print r.age
\newline
[31 15]
\newline
>>> print r.weight
\newline
[ 260.
145.]
\end_layout
\begin_layout Description
fromstring (datastring, dtype=None, shape=None, offset=0, formats=None,
names=None, titles=None, aligned=0, byteorder=None):
\end_layout
\begin_layout Description
\InsetSpace ~
Construct a record array using the provided datastring (at the given offset)
as the memory.
The record array will be read-only.
The byteorder argument may be used to specify the byteorder of all of the
fields at the same time.
A True aligned argument causes padding fields to be added as needed so
that the fields are aligned on boundaries determined by the compiler.
The shape of the returned array can also be specified.
\end_layout
\begin_layout Description
fromfile (fd, dtype=None, shape=None, offset=0, formats=None, names=None,
titles=None, aligned=False, byteorder=None)
\end_layout
\begin_layout Description
\InsetSpace ~
Construct a record array from the (binary) data in the given file object,
fd.
This object may be an open file or a string to indicate a file to read
from.
If offset is non-zero, then data is read from the file at offset bytes
from the current position.
\end_layout
\begin_layout Standard
The following classes are also available in the numpy.core (and therefore
the numpy) namespace
\end_layout
\begin_layout Description
record A subclass of the void array scalar type that allows field access
using attributes.
\end_layout
\begin_layout Description
recarray A subclass of the ndarray that allows field access using attributes
\end_layout
\begin_deeper
\begin_layout Description
__new__ (subtype, shape, formats, names=None, titles=None, buf=None, offset=0,
strides=None, byteorder=None, aligned=0)
\end_layout
\begin_layout Description
\InsetSpace ~
Construct an array of the given subtype and shape with data-type (record,
dtype) where dtype is constructed from formats, names, and titles.
If buf is None, then create new memory.
Otherwise, use the memory of buf exposed through the buffer protocol.
\end_layout
\end_deeper
\begin_layout Description
format_parser A class useful for creating a data-type descriptor from formats,
names, titles, and aligned arguments.
This is used by several of the record array constructors for consistency
in behavior.
\end_layout
\begin_deeper
\begin_layout Description
__init__ (self, formats, names, titles, aligned=False, byteorder=None)
\end_layout
\begin_layout Description
\InsetSpace ~
Construct a data-type object from formats, names, titles, aligned, and
byteorder arguments.
Upon completion the constructed data-type object is in self._descr.
\begin_inset LatexCommand index
name "record arrays|)"
\end_inset
\end_layout
\end_deeper
\begin_layout Section
Masked Arrays (numpy.ma)
\end_layout
\begin_layout Standard
\begin_inset LatexCommand index
name "masked arrays|("
\end_inset
These are adapted from the masked arrays provided with Numeric.
Masked Arrays do not inherit from the ndarray, they simply use two ndarray
objects in their internal representation.
Fortunately, as I have not used masked arrays in my work, Paul Dubois (the
original author of MA for Numeric) adapted and modified the code for use
by NumPy.
Alexander Belopolsky (Sasha) added additional functions and improvements
\end_layout
\begin_layout Standard
Masked arrays are created using the masked array creation function.
\end_layout
\begin_layout Description
ma.array (data, dtype=None, copy=True, order='C', mask=ma.nomask, fill_value=None)
\end_layout
\begin_deeper
\begin_layout Description
data Something that can be converted to an array.
If data is already a masked array, then if mask is ma.nomask, the mask used
be data.mask and the data used data.data.
\end_layout
\begin_layout Description
dtype The data-type of the underlying array
\end_layout
\begin_layout Description
copy If copy is False, then every effort will be made to not copy the data.
\end_layout
\begin_layout Description
order Specify whether the array is in 'C', 'Fortran', or 'Any' order
\end_layout
\begin_layout Description
mask Masked values are excluded from calculations.
If this is ma.nomask, then there are no masked values.
Otherwise, this should be an object that is convertible to an array of
Booleans with the same shape as data.
\end_layout
\begin_layout Description
fill_value This value is used to fill in masked values when necessary.
The fill_value is not used for computation for functions within the ma
module.
\end_layout
\end_deeper
\begin_layout Standard
Masked arrays have the same methods and attributes as arrays with the addition
of the mask attribute as well as the
\begin_inset Quotes eld
\end_inset
hidden
\begin_inset Quotes erd
\end_inset
attributes ._data and ._mask.
\begin_inset LatexCommand index
name "masked arrays|)"
\end_inset
\end_layout
\begin_layout Section
Standard container class
\end_layout
\begin_layout Standard
\begin_inset LatexCommand index
name "user\\_array"
\end_inset
\begin_inset LatexCommand index
name "container class"
\end_inset
For backward compatibility and as a standard
\begin_inset Quotes eld
\end_inset
container
\begin_inset Quotes erd
\end_inset
class, the UserArray from Numeric has been brought over to NumPy and named
\series bold
numpy.lib.user_array.container
\series default
The container class is a Python class whose self.array attribute is an ndarray.
Multiple inheritance is probably easier with numpy.lib.user_array.container
than with the ndarray itself and so it is included by default.
It is not documented here beyond mentioning its existence because you are
encouraged to use the ndarray class directly if you can.
\end_layout
\begin_layout Section
Array Iterators
\end_layout
\begin_layout Standard
\begin_inset LatexCommand index
name "array iterator"
\end_inset
Iterators are a powerful concept for array processing.
Essentially, iterators implement a generalized for-loop.
If myiter is an iterator object, then the Python code
\end_layout
\begin_layout LyX-Code
for val in myiter:
\end_layout
\begin_layout LyX-Code
...
\end_layout
\begin_layout LyX-Code
some code involving val
\end_layout
\begin_layout LyX-Code
...
\end_layout
\begin_layout Standard
calls val=myiter.next() repeatedly until StopIteration is raised by the iterator.
There are several ways to iterate over an array that may be useful: default
iteration, flat iteration, and
\begin_inset Formula $N$
\end_inset
-dimensional enumeration.
\end_layout
\begin_layout Subsection
Default iteration
\end_layout
\begin_layout Standard
The default iterator of an ndarray object is the default Python iterator
of a sequence type.
Thus, when the array object itself is used as an iterator.
The default behavior is equivalent to:
\end_layout
\begin_layout LyX-Code
for i in arr.shape[0]:
\end_layout
\begin_layout LyX-Code
val = arr[i]
\end_layout
\begin_layout Standard
This default iterator selects a sub-array of dimension
\begin_inset Formula $N-1$
\end_inset
from the array.
This can be a useful construct for defining recursive algorithms.
To loop over the entire array requires
\begin_inset Formula $N$
\end_inset
for-loops.
\end_layout
\begin_layout MyCode
>>> a = arange(24).reshape(3,2,4)+10
\newline
>>> for val in a:
\newline
...
print 'item:', val
\newline
item: [[10 11 12 13]
\newline
[14 15 16 17]]
\newline
item: [[18 19
20 21]
\newline
[22 23 24 25]]
\newline
item: [[26 27 28 29]
\newline
[30 31 32 33]]
\end_layout
\begin_layout Subsection
Flat iteration
\end_layout
\begin_layout Standard
As mentioned previously, the flat attribute of ndarray objects returns an
iterator that will cycle over the entire array in C-style contiguous order.
\end_layout
\begin_layout MyCode
>>> for i, val in enumerate(a.flat):
\newline
...
if i%5 == 0: print i, val
\newline
0 10
\newline
5 15
\newline
10 20
\newline
15 25
\newline
20 30
\end_layout
\begin_layout Standard
Here, I've used the built-in enumerate iterator to return the iterator index
as well as the value.
\end_layout
\begin_layout Subsection
N-dimensional enumeration
\end_layout
\begin_layout Standard
Sometimes it may be useful to get the N-dimensional index while iterating.
The ndenumerate iterator can achieve this.
\end_layout
\begin_layout MyCode
>>> for i, val in ndenumerate(a):
\newline
...
if sum(i)%5 == 0: print i, val
\newline
(0, 0, 0) 10
\newline
(1, 1, 3) 25
\newline
(2, 0, 3) 29
\newline
(2,
1, 2) 32
\end_layout
\begin_layout Subsection
Iterator for broadcasting
\end_layout
\begin_layout Standard
The general concept of broadcasting is also available from Python using
the
\series bold
broadcast
\series default
iterator.
This object takes
\begin_inset Formula $N$
\end_inset
objects as inputs and returns an iterator that returns tuples providing
each of the input sequence elements in the broadcasted result.
\end_layout
\begin_layout MyCode
>>> for val in broadcast([[1,0],[2,3]],[0,1]):
\newline
...
print val
\newline
(1, 0)
\newline
(0, 1)
\newline
(2, 0)
\newline
(3, 1)
\end_layout
\begin_layout Description
\InsetSpace ~
The methods and attributes of the broadcast object are:
\end_layout
\begin_deeper
\begin_layout Description
nd the number of dimensions in the broadcasted result.
\end_layout
\begin_layout Description
shape the shape of the broadcasted result.
\end_layout
\begin_layout Description
size the total size of the broadcasted result.
\end_layout
\begin_layout Description
index the current (flat) index into the broadcasted array
\end_layout
\begin_layout Description
iters a tuple of (broadcasted) NumPy.flatiter objects, one for each array.
\end_layout
\begin_layout Description
reset ()
\end_layout
\begin_layout Description
\InsetSpace ~
Reset the multiter object to the beginning.
\end_layout
\begin_layout Description
next ()
\end_layout
\begin_layout Description
\InsetSpace ~
Get the next tuple of objects from the (broadcasted) arrays
\end_layout
\end_deeper
\begin_layout Chapter
Universal Functions
\end_layout
\begin_layout Standard
\begin_inset LatexCommand label
name "par:The-Ufunc-Object"
\end_inset
\end_layout
\begin_layout Quotation
Computers make it easier to do a lot of things, but most of the things they
make it easier to do don't need to be done.
\end_layout
\begin_layout Right Address
---
\emph on
Andy Rooney
\end_layout
\begin_layout Quotation
People think computers will keep them from making mistakes.
They're wrong.
With computers you make mistakes faster.
\end_layout
\begin_layout Right Address
---
\emph on
Adam Osborne
\end_layout
\begin_layout Section
Description
\end_layout
\begin_layout Standard
\begin_inset LatexCommand index
name "ufunc|("
\end_inset
Universal functions are wrappers that provide a common interface to mathematical
functions that operate on scalars, and can be made to operate on arrays
in an element-by-element fashion.
All
\family typewriter
u
\family default
niversal
\family typewriter
func
\family default
tion
\family typewriter
s
\family default
(
\family typewriter
ufuncs
\family default
) wrap some core function that takes
\begin_inset Formula $n_{i}$
\end_inset
(scalar) inputs and produces
\begin_inset Formula $n_{o}$
\end_inset
(scalar) outputs.
Typically, this core function is implemented in compiled code but a Python
function can also be wrapped into a universal function using the basic
method
\family typewriter
frompyfunc
\family default
in the umath module.
\end_layout
\begin_layout Description
frompyfunc (func, nin, nout)
\begin_inset LatexCommand index
name "frompyfunc"
\end_inset
\end_layout
\begin_layout Description
\InsetSpace ~
This function returns a new universal function wrapping a Python function
func with nin inputs and nout outputs.
The resulting universal function works using Object arrays for both input
and output.
The vectorize class makes use of frompyfunc internally.
You can view the source code using numpy.source(numpy.vectorize).
\end_layout
\begin_layout Subsection
Broadcasting
\end_layout
\begin_layout Standard
\begin_inset LatexCommand index
name "broadcasting"
\end_inset
Each universal function takes array inputs and produces array outputs by
performing the core function element-wise on the inputs.
The standard broadcasting rules are applied so that inputs without exactly
the same shapes can still be usefully operated on.
Broadcasting can be understood by four rules:
\end_layout
\begin_layout Enumerate
All input arrays with ndim smaller than the input array of largest ndim
have 1's pre-pended to their shapes.
\end_layout
\begin_layout Enumerate
The size in each dimension of the output shape is the maximum of all the
input shapes in that dimension.
\end_layout
\begin_layout Enumerate
An input can be used in the calculation if it's shape in a particular dimension
either matches the output shape or has value exactly 1.
\end_layout
\begin_layout Enumerate
If an input has a dimension size of 1 in its shape, the first data entry
in that dimension will be used for all calculations along that dimension.
In other words, the stepping machinery of the ufunc will simply not step
along that dimension when otherwise needed (the stride will be 0 for that
dimension).
\end_layout
\begin_layout Standard
While perhaps a bit difficult to explain, broadcasting can be quite useful
and becomes second nature rather quickly.
Broadcasting is used throughout NumPy to decide how to handle non equally-shape
d arrays.
\end_layout
\begin_layout Subsection
Output type determination
\end_layout
\begin_layout Standard
The output of the ufunc (and its methods) does not have to be an ndarray.
All output arrays will be passed to the __array_wrap__ method of any input
(besides ndarrays, and scalars) that defines it
\series bold
and
\series default
has the highest __array_priority__ of any other input to the universal
function.
The default __array_priority__ of the ndarray is 0.0, and the default __array_pr
iority__ of a subtype is 1.0.
Matrices have __array_priority__ equal to 10.0.
\end_layout
\begin_layout Standard
The ufuncs can also all take output arguments.
The output will be cast if necessary to the provided output array.
If a class with an __array__ method is used for the output, results will
be written to the object returned by __array__.
Then, if the class also has an __array_wrap__ method, the returned
\family typewriter
ndarray
\family default
result will be passed to that method just before passing control back to
the caller.
\end_layout
\begin_layout Subsection
Use of internal buffers
\end_layout
\begin_layout Standard
Internally, buffers are used for misaligned data, swapped data, and data
that has to be converted from one data type to another.
The size of the internal buffers is settable on a per-thread basis.
There can be up to
\begin_inset Formula $2\left(n_{i}+n_{o}\right)$
\end_inset
buffers of the specified size created to handle the data from all the inputs
and outputs of a ufunc.
The default size of the buffer is 10,000 elements.
Whenever buffer-based calculation would be needed, but all input arrays
are smaller than the buffer size, those misbehaved or incorrect typed arrays
will be copied before the calculation proceeds.
Adjusting the size of the buffer may therefore alter the speed at which
ufunc calculations of various sorts are completed.
A simple interface for setting this variable is accessible using the function
\end_layout
\begin_layout Description
setbufsize (size)
\begin_inset LatexCommand index
name "setbufsize"
\end_inset
\end_layout
\begin_layout Description
\InsetSpace ~
Set the buffer size to the given number of elements in the current thread.
Return the old buffer size (so that it can be reset later if desired).
\end_layout
\begin_layout Subsection
Error handling
\end_layout
\begin_layout Standard
\begin_inset LatexCommand index
name "error handling"
\end_inset
Universal functions can trip special floating point status registers in
your hardware (such as divide-by-zero).
If available on your platform, these registers will be regularly checked
during calculation.
The user can determine what should be done if errors are encountered.
Error handling is controlled on a per-thread basis.
Four errors can be individually configured: divide-by-zero, overflow, underflow
, and invalid.
The errors can each be set to ignore, warn, raise, or call.
The easiest way to configure the error mask is using the function
\end_layout
\begin_layout Description
seterr (all=None, divide=None, over=None, under=None, invalid=None)
\end_layout
\begin_layout Description
\InsetSpace ~
\begin_inset LatexCommand index
name "seterr"
\end_inset
This will set the current thread so that errors can be handled if desired.
If one of the errors is set to 'call', then a function must be provided
using the seterrcall() routine.
If any of the arguments are None, then that error mask will be unchanged.
The return value of this function is a dictionary with the old error conditions.
Thus, you can restore the old condition after you are finished with your
function by calling seterr(**old).
If all is set, then all errors will be set to the specified value.
\end_layout
\begin_layout Description
seterrcall (callable)
\end_layout
\begin_layout Description
\InsetSpace ~
\begin_inset LatexCommand index
name "seterrcall"
\end_inset
This sets the function to call when an error is triggered for an error condition
configured with the
\begin_inset Quotes eld
\end_inset
call
\begin_inset Quotes erd
\end_inset
handler.
This function should take two arguments: a string showing the type of error
that triggered the call, and an integer showing the state of the floating
point status registers.
Any return value of the call function will be ignored, but errors can be
raised by the function.
Only one error function handler can be specified for all the errors.
The status argument shows which errors were raised.
The return value of this routine is the old callable.
The argument passed in to this function must be any callable object with
the right signature or None.
\end_layout
\begin_layout Note
FPE_DIVIDEBYZERO, FPE_OVERFLOW, FPE_UNDERFLOW, and FPE_INVALID, are all
defined constants in NumPy.
The status flag returned for a 'call' error handling type shows which errors
were raised by adding these constants together.
\end_layout
\begin_layout Subsection
Optional keyword arguments
\end_layout
\begin_layout Standard
\begin_inset LatexCommand index
name "ufunc!keyword arguments"
\end_inset
All ufuncs take optional keyword arguments.
These represent rather advanced usage and will likely not be used by most
users.
\end_layout
\begin_layout Description
sig= either a data-type, a tuple of data-types, or a special signature string
indicating the input and output types of a ufunc.
This argument allows you to specify a specific signature for a the 1-d
loop to use in the underlying calculation.
If the loop specified does not exist for the ufunc, then a TypeError is
raised.
Normally a suitable loop is found automatically by comparing the input
types with what is available and searching for a loop with data-types to
which all inputs can be cast safely.
This key-word argument lets you by-pass that search and choose a loop you
want.
A list of available signatures is available in the
\series bold
types
\series default
attribute of the ufunc object.
\end_layout
\begin_layout Description
extobj= a list of length 1, 2, or 3 specifying the ufunc buffer-size, the
error mode integer, and the error call-back function.
Normally, these values are looked-up in a thread-specific dictionary.
Passing them here bypasses that look-up and uses the low-level specification
provided for the error-mode.
This may be useful as an optimization for calculations requiring lots of
ufuncs on small arrays in a loop.
\end_layout
\begin_layout Section
Attributes
\end_layout
\begin_layout Standard
\begin_inset LatexCommand index
name "ufunc!attributes"
\end_inset
There are some informational attributes that universal functions possess.
None of the attributes can be set.
\end_layout
\begin_layout Description
__doc__
\end_layout
\begin_layout Description
\InsetSpace ~
A docstring for each ufunc.
The first part of the docstring is dynamically generated from the number
of outputs, the name, and the number of inputs.
The second part of the doc string is provided at creation time and stored
with the ufunc.
\end_layout
\begin_layout Description
__name__
\end_layout
\begin_layout Description
\InsetSpace ~
The name of this ufunc.
\end_layout
\begin_layout Description
nin
\end_layout
\begin_layout Description
\InsetSpace ~
The number of inputs
\end_layout
\begin_layout Description
nout
\end_layout
\begin_layout Description
\InsetSpace ~
The number of outputs
\end_layout
\begin_layout Description
nargs
\end_layout
\begin_layout Description
\InsetSpace ~
The total number of inputs + outputs
\end_layout
\begin_layout Description
ntypes
\end_layout
\begin_layout Description
\InsetSpace ~
The total number of different types for which this ufunc is defined.
\end_layout
\begin_layout Description
types
\end_layout
\begin_layout Description
\InsetSpace ~
A list of length ntypes containing strings showing the types for which
this ufunc is defined.
Other types may still be used as inputs (and as output arrays), they will
just need casting.
For inputs, standard casting rules will be used to determine which of the
supplied internal functions that will be used (and therefore the default
type of the output).
Results will always be force-cast to any array provided to hold the output.
\end_layout
\begin_layout Description
identity
\end_layout
\begin_layout Description
\InsetSpace ~
A 1, 0, or None to show the identity for this universal function.
This identity is used for reduction on zero-sized arrays (arrays with a
shape that includes a 0).
\end_layout
\begin_layout Standard
\begin_inset Float table
wide false
sideways false
status open
\begin_layout Standard
\begin_inset Caption
\begin_layout Standard
Universal function (ufunc) attributes.
\end_layout
\end_inset
\end_layout
\begin_layout Standard
\align center
\begin_inset Tabular
\begin_inset Text
\begin_layout Standard
Name
\end_layout
\end_inset
|
\begin_inset Text
\begin_layout Standard
Description
\end_layout
\end_inset
|
\begin_inset Text
\begin_layout Standard
__doc__
\end_layout
\end_inset
|
\begin_inset Text
\begin_layout Standard
Dynamic docstring.
\end_layout
\end_inset
|
\begin_inset Text
\begin_layout Standard
__name__
\end_layout
\end_inset
|
\begin_inset Text
\begin_layout Standard
Name of ufunc
\end_layout
\end_inset
|
\begin_inset Text
\begin_layout Standard
nin
\end_layout
\end_inset
|
\begin_inset Text
\begin_layout Standard
Number of input arguments
\end_layout
\end_inset
|
\begin_inset Text
\begin_layout Standard
nout
\end_layout
\end_inset
|
\begin_inset Text
\begin_layout Standard
Number of output arguments
\end_layout
\end_inset
|
\begin_inset Text
\begin_layout Standard
nargs
\end_layout
\end_inset
|
\begin_inset Text
\begin_layout Standard
Total number of arguments
\end_layout
\end_inset
|
\begin_inset Text
\begin_layout Standard
ntypes
\end_layout
\end_inset
|
\begin_inset Text
\begin_layout Standard
Number of defined inner loops.
\end_layout
\end_inset
|
\begin_inset Text
\begin_layout Standard
types
\end_layout
\end_inset
|
\begin_inset Text
\begin_layout Standard
List showing types for which inner loop is defined.
\end_layout
\end_inset
|
\begin_inset Text
\begin_layout Standard
identity
\end_layout
\end_inset
|
\begin_inset Text
\begin_layout Standard
Identity for this ufunc.
\end_layout
\end_inset
|
\end_inset
\end_layout
\end_inset
\end_layout
\begin_layout Section
Casting Rules
\end_layout
\begin_layout Standard
\begin_inset LatexCommand index
name "ufunc!casting rules"
\end_inset
At the core of every ufunc is a one-dimensional strided loop that implements
the actual function for a specific type combination.
When a ufunc is created, it is given a static list of inner loops and a
corresponding list of type signatures over which the ufunc operates.
The ufunc machinery uses this list to determine which inner loop to use
for a particular case.
You can inspect the
\family typewriter
.types
\family default
attribute for a particular ufunc to see which type combinations have a
defined inner loop and which output type they produce (the character codes
are used in that output for brevity).
\end_layout
\begin_layout Standard
Casting must be done on one or more of the inputs whenever the ufunc does
not have a core loop implementation for the input types provided.
If an implementation for the input types cannot be found, then the algorithm
searches for an implementation with a type signature to which all of the
inputs can be cast
\begin_inset Quotes eld
\end_inset
safely.
\begin_inset Quotes erd
\end_inset
The first one it finds in its internal list of loops is selected and performed
with types cast.
Recall that internal copies during ufuncs (even for casting) are limited
to the size of an internal buffer which is user settable.
\end_layout
\begin_layout Note
Universal functions in NumPy are flexible enough to have mixed type signatures.
Thus, for example, a universal function could be defined that works with
floating point and integer values.
See ldexp for an example.
\end_layout
\begin_layout Standard
By the above description, the casting rules are essentially implemented
by the question of when a data type can be cast
\begin_inset Quotes eld
\end_inset
safely
\begin_inset Quotes erd
\end_inset
to another data type.
The answer to this question can be determined in Python with a function
call: can_cast (fromtype, totype).
Figure shows the results of this call for my 32-bit system on the 21 internally
supported types.
You can generate this table for your system with code shown in that Figure.
\end_layout
\begin_layout Standard
\begin_inset Float figure
wide false
sideways false
status open
\begin_layout MyCode
>>> def print_table(ntypes):
\newline
...
print 'X',
\newline
...
for char in ntypes: print char,
\newline
...
print
\newline
...
for row in ntypes:
\newline
...
print row,
\newline
...
for col in ntypes:
\newline
...
print int(can_cast(row, col)),
\newline
...
print
\newline
>>> print_table(typecodes['All'])
\newline
X ? b h i l q p B H I L Q
P f d g F D G S U V O
\newline
? 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1
\newline
b 0
1 1 1 1 1 1 0 0 0 0 0 0 1 1 1 1 1 1 1 1 1 1
\newline
h 0 0 1 1 1 1 1 0 0 0 0 0 0
1 1 1 1 1 1 1 1 1 1
\newline
i 0 0 0 1 1 1 1 0 0 0 0 0 0 0 1 1 0 1 1 1 1 1 1
\newline
l 0 0
0 1 1 1 1 0 0 0 0 0 0 0 1 1 0 1 1 1 1 1 1
\newline
q 0 0 0 0 0 1 0 0 0 0 0 0 0 0
1 1 0 1 1 1 1 1 1
\newline
p 0 0 0 1 1 1 1 0 0 0 0 0 0 0 1 1 0 1 1 1 1 1 1
\newline
B 0 0 1
1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1
\newline
H 0 0 0 1 1 1 1 0 1 1 1 1 1 1 1
1 1 1 1 1 1 1 1
\newline
I 0 0 0 0 0 1 0 0 0 1 1 1 1 0 1 1 0 1 1 1 1 1 1
\newline
L 0 0 0 0
0 1 0 0 0 1 1 1 1 0 1 1 0 1 1 1 1 1 1
\newline
Q 0 0 0 0 0 0 0 0 0 0 0 1 0 0 1 1
0 1 1 1 1 1 1
\newline
P 0 0 0 0 0 1 0 0 0 1 1 1 1 0 1 1 0 1 1 1 1 1 1
\newline
f 0 0 0 0 0
0 0 0 0 0 0 0 0 1 1 1 1 1 1 1 1 1 1
\newline
d 0 0 0 0 0 0 0 0 0 0 0 0 0 0 1 1 0
1 1 1 1 1 1
\newline
g 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 1 0 0 1 1 1 1 1
\newline
F 0 0 0 0 0 0
0 0 0 0 0 0 0 0 0 0 1 1 1 1 1 1 1
\newline
D 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 1
1 1 1 1 1
\newline
G 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 1 1 1 1 1
\newline
S 0 0 0 0 0 0 0
0 0 0 0 0 0 0 0 0 0 0 0 1 1 1 1
\newline
U 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0
0 1 1 1
\newline
V 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 1 1
\newline
O 0 0 0 0 0 0 0 0
0 0 0 0 0 0 0 0 0 0 0 0 0 1 1
\end_layout
\begin_layout Standard
\begin_inset Caption
\begin_layout Standard
Code segment showing the can cast safely table for a 32-bit system.
\end_layout
\end_inset
\end_layout
\end_inset
\end_layout
\begin_layout Standard
You should note that, while included in the table for completeness, the
'S', 'U', and 'V' types cannot be operated on by ufuncs.
Also, note that on a 64-bit system the integer types may have different
sizes resulting in a slightly altered table.
\end_layout
\begin_layout Standard
Mixed scalar-array operations use a different set of casting rules that
ensure that a scalar cannot upcast an array unless the scalar is of a fundament
ally different kind of data (
\emph on
i.e.
\emph default
under a different hierachy in the data type hierarchy) then the array.
This rule enables you to use scalar constants in your code (which as Python
types are interpreted accordingly in ufuncs) without worrying about whether
the precision of the scalar constant will cause upcasting on your large
(small precision) array.
\end_layout
\begin_layout Section
Methods
\end_layout
\begin_layout Standard
\begin_inset LatexCommand index
name "ufunc!methods|("
\end_inset
All ufuncs have 4 methods.
However, these methods only make sense on ufuncs that take two input arguments
and return one output argument.
Attempting to call these methods on other ufuncs will cause a
\family typewriter
ValueError
\family default
.
The reduce-like methods all take an axis keyword and a dtype keyword, and
the arrays must all have dimension >= 1.
The
\emph on
axis
\emph default
keyword specifies which axis of the array the reduction will take place
over and may be negative, but must be an integer.
The
\emph on
dtype
\emph default
keyword allows you to manage a very common problem that arises when naively
using .reduce.
Sometimes you may have an array of a certain data type and wish to add
up all of its elements, but the result does not fit into the data type
of the array.
This commonly happens if you have an array of single-byte integers.
The dtype keyword allows you to alter the data type that the reduction
takes place over (and therefore the type of the output).
Thus, you can ensure that the output is a data type with large-enough precision
to handle your output.
The responsibility of altering the reduce type is mostly up to you.
There is one exception: if no dtype is given for a reduction on the
\begin_inset Quotes eld
\end_inset
add
\begin_inset Quotes erd
\end_inset
or
\begin_inset Quotes eld
\end_inset
multiply
\begin_inset Quotes erd
\end_inset
operations, then if the input type is an integer (or boolean) data-type
and smaller than the size of the int_ data type, it will be internally
upcast to the int_ (or uint) data type.
\end_layout
\begin_layout Warning
A reduce-like operation on an array with a data type that has range
\begin_inset Quotes eld
\end_inset
too small
\begin_inset Quotes erd
\end_inset
to handle the result will silently wrap.
You should use dtype to increase the data type over which reduction takes
place.
\end_layout
\begin_layout Subsection
Reduce
\end_layout
\begin_layout Description
.reduce (array=, axis=0, dtype=None)
\end_layout
\begin_layout Description
\InsetSpace ~
\begin_inset LatexCommand index
name "ufunc!methods!reduce"
\end_inset
For each one-dimensional sequence along the
\emph on
axis
\emph default
dimension of the array, return a single number resulting from recursively
applying the operation to succesive elements along that dimension.
If the input array has
\begin_inset Formula $N$
\end_inset
dimensions, then the returned array has
\begin_inset Formula $N-1$
\end_inset
dimensions.
This produces the equivalent of the following Python code :
\end_layout
\begin_layout LyX-Code
>>> indx = [index_exp[:]]*array.ndim
\newline
>>> indx[axis] = 0; N=array.shape[axis]
\newline
>>>
result = array[indx].astype(dtype)
\newline
>>> for i in range(1,N):
\newline
...
indx[axis] = i
\newline
...
(result, array[indx], result)
\end_layout
\begin_layout Description
\InsetSpace ~
Studying the above code can also help you gain an appreciation for how
to do generic indexing in Python using
\family typewriter
index_exp
\family default
.
For example, if is add, then .reduce produces a summation along
the given axis.
If is prod, then a repeated multiply is performed.
\end_layout
\begin_layout Subsection
Accumulate
\end_layout
\begin_layout Description
.accumulate (array=, axis=0, dtype=None)
\end_layout
\begin_layout Description
\InsetSpace ~
\begin_inset LatexCommand index
name "ufunc!methods!accumulate"
\end_inset
This method is similar to reduce, except it returns an array of the same
shape as the input, and keeps intermediate calculations.
The operation is still performed along the access.
This method underlies the operations of the cumsum and cumprod methods
of arrays.
The following Python code implements an equivalent of the accumulate method.
\end_layout
\begin_layout LyX-Code
>>> i1 = [index_exp[:]]*array.ndim
\newline
>>> i2 = [index_exp[:]]*array.ndim
\newline
>>> i1[axis]
= 0; N=array.shape[axis]
\newline
>>> result = array.astype(dtype)
\newline
>>> for i in range(1,N):
\newline
...
i1[axis] = i
\newline
...
i2[axis] = i-1
\newline
...
(result[i1], array[i1], result[i2])
\end_layout
\begin_layout Subsection
Reduceat
\end_layout
\begin_layout Description
.reduceat (array=, indices=, axis=0, dtype=None)
\end_layout
\begin_layout Description
\InsetSpace ~
\begin_inset LatexCommand index
name "ufunc!methods!reduceat"
\end_inset
This method is a generalization of both reduce and accumulate.
It offers the ability to reduce along an axis but only between certain
indices.
The indices input must be a one dimensional (index) sequence.
Then, if
\begin_inset Formula $I_{k}$
\end_inset
is the
\begin_inset Formula $k^{\textrm{th}}$
\end_inset
element of indices, the reduceat method computes .reduce(array[
\begin_inset Formula $I_{k}$
\end_inset
:
\begin_inset Formula $I_{k+1}$
\end_inset
]).
This formula assumes
\begin_inset Formula $I_{k+1}>I_{k}$
\end_inset
, and also that
\begin_inset Formula $I_{k+1}$
\end_inset
is the length of the input array when
\begin_inset Formula $I_{k}$
\end_inset
is the last element.
There is no requirement that the indices be monotonic.
If
\begin_inset Formula $I_{k+1}\leq I_{k},$
\end_inset
then reduceat simply returns array[
\begin_inset Formula $I_{k}$
\end_inset
] for that particular element of indices.
In these formulas, we have assumed that array is one dimensional (or axis
is 0).
If the array is
\begin_inset Formula $N$
\end_inset
-dimensional and axis>0, then the index expression needs axis ':' (full
slice objects) inserted (i.e.
array[
\begin_inset Formula $\underbrace{:,\ldots,:}_{\textrm{axis}},I_{k}:I_{k+1}$
\end_inset
]).
The effect is to slice along the axis dimension.
Equivalent Python code is
\end_layout
\begin_layout LyX-Code
>>> i1 = [index_exp[:]]*array.ndim
\newline
>>> i2 = [index_exp[:]]*array.ndim
\newline
>>> outshape
= list(array.shape)
\newline
>>> N = array.shape[axis]
\newline
>>> outshape[axis] = len(indices)
\newline
>>>
result = zeros(outshape, dtype or array.dtype)
\newline
>>> for k,Ik in enumerate(indices
):
\newline
...
i1[axis] = k
\newline
...
try:
\newline
...
Ikp1 = indices[k+1]
\newline
...
except IndexError:
\newline
...
Ikp1 = N
\newline
...
if (Ikp1 > Ik):
\end_layout
\begin_layout LyX-Code
...
i2[axis] = index_exp[Ik:Ikp1]
\newline
...
result[i1] = .reduce(array[i2],axis=axis,dtype=dtype)
\newline
...
else:
\newline
...
result[i1] = array[Ik].astype(dtype)
\end_layout
\begin_layout Description
\InsetSpace ~
The returned array has as many dimensions as the input array, and is the
same shape except for the
\emph on
axis
\emph default
dimension which has shape equal to the length of indices (the number of
reduce operations that were performed).
If you ever have a need to compute multiple reductions over portions of
an array, then (if you can get your mind around what it is doing) reduceat
may be just what you were looking for.
\end_layout
\begin_deeper
\begin_layout Description
Example: Suppose a is a two-dimensional array of shape
\begin_inset Formula $10\times20$
\end_inset
.
Then, res=add.reduce (a, [0,3,1]) returns a
\begin_inset Formula $3\times20$
\end_inset
array with res[0,:] = add.reduce(a[:,0:3]), res[1,:] = a[:,3], and res[2,:]
= add.reduce(a[:,1:]).
\end_layout
\end_deeper
\begin_layout Subsection
Outer
\end_layout
\begin_layout Description
.outer (a, b)
\end_layout
\begin_layout Description
\InsetSpace ~
\begin_inset LatexCommand index
name "ufunc!methods!outer"
\end_inset
This method computes an outer operation on .
It computes (a2, b2) where a2 is 'a' with b.ndim 1's post-pended to
it's shape and b2 is 'b' with a.ndim 1's pre-pended to its shape (broadcasting
takes care of this automatically in the code below).
The return shape has a.ndim + b.ndim dimensions.
Equivalent Python code is
\end_layout
\begin_layout LyX-Code
>>> a.shape += (1,)*b.ndim
\newline
>>> (a,b)
\newline
>>> a = a.squeeze()
\end_layout
\begin_layout Standard
\InsetSpace ~
Among many other uses, arithmetic tables can be conveniently built using
outer:
\begin_inset LatexCommand index
name "ufunc!methods|)"
\end_inset
\end_layout
\begin_layout MyCode
>>> multiply.outer([1,7,9,12],arange(5,12))
\newline
array([[ 5, 6, 7, 8,
9, 10, 11],
\newline
[ 35, 42, 49, 56, 63, 70, 77],
\newline
[ 45, 54,
63, 72, 81, 90, 99],
\newline
[ 60, 72, 84, 96, 108, 120, 132]])
\end_layout
\begin_layout Section
Available ufuncs
\end_layout
\begin_layout Standard
There are currently more than 60 universal functions defined on one or more
types, covering a wide variety of operations.
Some of these ufuncs are called automatically on arrays when the relevant
infix notation is used (i.e.
add(a,b) is called internally when a + b is written and a or b is an ndarray).
Nonetheless, you may still want to use the ufunc call in order to use the
optional output argument(s) to place the output(s) in an object (or in
objects) of your choice.
\end_layout
\begin_layout Standard
Recall that each ufunc operates element-by-element.
Therefore, each ufunc will be described as if acting on a set of scalar
inputs to return a set of scalar outputs.
\end_layout
\begin_layout Note
The ufunc still returns its output(s) even if you use the optional output
argument(s).
\end_layout
\begin_layout Subsection
Math operations
\end_layout
\begin_layout Description
add (
\begin_inset Formula $x_{1}$
\end_inset
,
\begin_inset Formula $x_{2}$
\end_inset
[,
\begin_inset Formula $y$
\end_inset
])
\begin_inset LatexCommand index
name "add"
\end_inset
\end_layout
\begin_layout Description
\InsetSpace ~
\begin_inset Formula $y=x_{1}+x_{2}$
\end_inset
.
Called to implement
\family typewriter
x1+x2
\family default
for arrays
\end_layout
\begin_layout Description
subtract (
\begin_inset Formula $x_{1}$
\end_inset
,
\begin_inset Formula $x_{2}$
\end_inset
[,
\begin_inset Formula $y$
\end_inset
])
\begin_inset LatexCommand index
name "subtract"
\end_inset
\end_layout
\begin_layout Description
\InsetSpace ~
\begin_inset Formula $y=x_{1}-x_{2}$
\end_inset
.
Called to implement
\family typewriter
x1-x2
\family default
for arrays
\end_layout
\begin_layout Description
multiply (
\begin_inset Formula $x_{1}$
\end_inset
,
\begin_inset Formula $x_{2}$
\end_inset
[,
\begin_inset Formula $y$
\end_inset
])
\begin_inset LatexCommand index
name "multiply"
\end_inset
\end_layout
\begin_layout Description
\InsetSpace ~
\begin_inset Formula $y=x_{1}\cdot x_{2}$
\end_inset
.
Called to implement
\family typewriter
x1*x2
\family default
for arrays.
\end_layout
\begin_layout Description
divide (
\begin_inset Formula $x_{1}$
\end_inset
,
\begin_inset Formula $x_{2}$
\end_inset
[,
\begin_inset Formula $y$
\end_inset
])
\begin_inset LatexCommand index
name "divide"
\end_inset
\end_layout
\begin_layout Description
\InsetSpace ~
\begin_inset Formula $y=x_{1}/x_{2}$
\end_inset
Integer division results in truncation.
Floating-point does not.
Called to implement
\family typewriter
x1/x2
\family default
for arrays (when __future__.division is not active).
\end_layout
\begin_layout Description
true_divide (
\begin_inset Formula $x_{1}$
\end_inset
,
\begin_inset Formula $x_{2}$
\end_inset
[,
\begin_inset Formula $y$
\end_inset
])
\begin_inset LatexCommand index
name "true\\_divide"
\end_inset
\end_layout
\begin_layout Description
\InsetSpace ~
This version of division always returns an inexact number so that integer
division returns floating point.
Called with __future__.division is active to implement
\family typewriter
x1/x2
\family default
for arrays.
\end_layout
\begin_layout Description
floor_divide (
\begin_inset Formula $x_{1}$
\end_inset
,
\begin_inset Formula $x_{2}$
\end_inset
[,
\begin_inset Formula $y$
\end_inset
])
\begin_inset LatexCommand index
name "floor\\_divide"
\end_inset
\end_layout
\begin_layout Description
\InsetSpace ~
This version of division always results in truncation of an fractional
part remaining.
Called to implement
\family typewriter
x1//x2
\family default
for arrays.
\end_layout
\begin_layout Description
negative (
\begin_inset Formula $x$
\end_inset
[,
\begin_inset Formula $y$
\end_inset
])
\begin_inset LatexCommand index
name "negative"
\end_inset
\end_layout
\begin_layout Description
\InsetSpace ~
\begin_inset Formula $y=-x$
\end_inset
.
Called to implement
\family typewriter
-x
\family default
for arrays.
\end_layout
\begin_layout Description
power (
\begin_inset Formula $x_{1}$
\end_inset
,
\begin_inset Formula $x_{2}$
\end_inset
[,
\begin_inset Formula $y$
\end_inset
])
\begin_inset LatexCommand index
name "power"
\end_inset
\end_layout
\begin_layout Description
\InsetSpace ~
\begin_inset Formula $y=x_{1}^{x_{2}}$
\end_inset
.
There is no three-term power ufunc defined.
This two-term power function is called to implement
\family typewriter
pow(x1,x2,)
\family default
or
\family typewriter
x1**x2
\family default
for arrays.
Note that the third term in
\family typewriter
pow
\family default
is ignored for array arguments.
\end_layout
\begin_layout Description
remainder (
\begin_inset Formula $x_{1}$
\end_inset
,
\begin_inset Formula $x_{2}$
\end_inset
[,
\begin_inset Formula $y$
\end_inset
])
\begin_inset LatexCommand index
name "remainder"
\end_inset
\end_layout
\begin_layout Description
\InsetSpace ~
Returns
\begin_inset Formula $x-y$
\end_inset
*floor(
\begin_inset Formula $x/y$
\end_inset
).
Result has the sign of
\begin_inset Formula $y$
\end_inset
.
Called to implement
\family typewriter
x1%x2
\family default
.
\end_layout
\begin_layout Description
mod (
\begin_inset Formula $x_{1}$
\end_inset
,
\begin_inset Formula $x_{2}$
\end_inset
[,
\begin_inset Formula $y$
\end_inset
])
\end_layout
\begin_layout Description
\InsetSpace ~
Same as remainder (
\begin_inset Formula $x_{1}$
\end_inset
,
\begin_inset Formula $x_{2}$
\end_inset
[,
\begin_inset Formula $y$
\end_inset
]).
\end_layout
\begin_layout Description
fmod (
\begin_inset Formula $x_{1}$
\end_inset
,
\begin_inset Formula $x_{2}$
\end_inset
[,
\begin_inset Formula $y$
\end_inset
])
\end_layout
\begin_layout Description
\InsetSpace ~
\begin_inset Formula $x_{1}=kx_{2}+y$
\end_inset
where
\begin_inset Formula $k$
\end_inset
is the largest integer satisfying this equation.
Computes C-like
\begin_inset Formula $x_{1}\%x_{2}$
\end_inset
element-wise.
This was the behavior of
\family typewriter
x1%x2
\family default
in old Numeric.
\end_layout
\begin_layout Description
absolute (
\begin_inset Formula $x$
\end_inset
[,
\begin_inset Formula $y$
\end_inset
])
\begin_inset LatexCommand index
name "absolute"
\end_inset
\end_layout
\begin_layout Description
\InsetSpace ~
\begin_inset Formula $y=\left|x\right|.$
\end_inset
Called to implement
\family typewriter
abs(x)
\family default
for arrays.
\end_layout
\begin_layout Description
rint (x, [, y])
\end_layout
\begin_layout Description
\InsetSpace ~
Round
\begin_inset Formula $x$
\end_inset
to the nearest integer.
Rounds half-way cases to the nearest even integer.
\end_layout
\begin_layout Description
sign (
\begin_inset Formula $x$
\end_inset
[,
\begin_inset Formula $y$
\end_inset
])
\end_layout
\begin_layout Description
\InsetSpace ~
Sets
\begin_inset Formula $y$
\end_inset
according to
\begin_inset Formula \[
\textrm{sign}\left(x\right)=\left\{ \begin{array}{cc}
1 & x:>0,\\
0 & x=0,\\
-1 & x<0.\end{array}\right.\]
\end_inset
\end_layout
\begin_layout Description
conj (
\begin_inset Formula $x$
\end_inset
[,
\begin_inset Formula $y$
\end_inset
])
\begin_inset LatexCommand index
name "conj"
\end_inset
\end_layout
\begin_layout Description
conjugate (
\begin_inset Formula $x$
\end_inset
[,
\begin_inset Formula $y$
\end_inset
])
\begin_inset LatexCommand index
name "conjugate"
\end_inset
\end_layout
\begin_layout Description
\InsetSpace ~
\begin_inset Formula $y=\overline{x}$
\end_inset
; in other words, the complex conjugate of
\begin_inset Formula $x$
\end_inset
.
\end_layout
\begin_layout Description
exp (
\begin_inset Formula $x$
\end_inset
[,
\begin_inset Formula $y$
\end_inset
])
\begin_inset LatexCommand index
name "exp"
\end_inset
\end_layout
\begin_layout Description
\InsetSpace ~
\begin_inset Formula $y=e^{x}.$
\end_inset
\end_layout
\begin_layout Description
log (
\begin_inset Formula $x$
\end_inset
[,
\begin_inset Formula $y$
\end_inset
])
\begin_inset LatexCommand index
name "log"
\end_inset
\end_layout
\begin_layout Description
\InsetSpace ~
\begin_inset Formula $y=\log\left(x\right)$
\end_inset
.
In other words,
\begin_inset Formula $y$
\end_inset
is the number so that
\begin_inset Formula $e^{y}=x$
\end_inset
.
\end_layout
\begin_layout Description
expm1 (
\begin_inset Formula $x$
\end_inset
, [,
\begin_inset Formula $y$
\end_inset
])
\end_layout
\begin_layout Description
\InsetSpace ~
\begin_inset Formula $y=e^{x}-1.$
\end_inset
Calculated so that it is accurate for small
\begin_inset Formula $\left|x\right|.$
\end_inset
\end_layout
\begin_layout Description
log1p (
\begin_inset Formula $x$
\end_inset
, [,
\begin_inset Formula $y$
\end_inset
])
\end_layout
\begin_layout Description
\InsetSpace ~
\begin_inset Formula $y=\log\left(1+x\right)$
\end_inset
but accurate for small
\begin_inset Formula $\left|x\right|.$
\end_inset
Returns the number
\begin_inset Formula $y$
\end_inset
such that
\begin_inset Formula $e^{y}-1=x$
\end_inset
\end_layout
\begin_layout Description
log10 (
\begin_inset Formula $x$
\end_inset
[,
\begin_inset Formula $y$
\end_inset
])
\begin_inset LatexCommand index
name "log10"
\end_inset
\end_layout
\begin_layout Description
\InsetSpace ~
\begin_inset Formula $y=\log10\left(x\right)$
\end_inset
.
In other words,
\begin_inset Formula $y$
\end_inset
is the number so that
\begin_inset Formula $10^{y}=x.$
\end_inset
\end_layout
\begin_layout Description
sqrt (
\begin_inset Formula $x$
\end_inset
[,
\begin_inset Formula $y$
\end_inset
])
\begin_inset LatexCommand index
name "sqrt"
\end_inset
\end_layout
\begin_layout Description
\InsetSpace ~
\begin_inset Formula $y=\sqrt{x}.$
\end_inset
\end_layout
\begin_layout Description
square (
\begin_inset Formula $x$
\end_inset
[,
\begin_inset Formula $y$
\end_inset
])
\end_layout
\begin_layout Description
\InsetSpace ~
\begin_inset Formula $y=x*x$
\end_inset
\end_layout
\begin_layout Description
reciprocal (
\begin_inset Formula $x$
\end_inset
[,
\begin_inset Formula $y$
\end_inset
])
\end_layout
\begin_layout Description
\InsetSpace ~
\begin_inset Formula $y=1/x$
\end_inset
\end_layout
\begin_layout Description
ones_like (
\begin_inset Formula $x$
\end_inset
, [,
\begin_inset Formula $y$
\end_inset
])
\end_layout
\begin_layout Description
\InsetSpace ~
\begin_inset Formula $y=1$
\end_inset
If an output argument is not given the returned data-type is the same as
the input data type.
\end_layout
\begin_layout Tip
The optional output arguments can be used to help you save memory for large
calculations.
If your arrays are large, complicated expressions can take longer than
absolutely necessary due to the creation and (later) destruction of temporary
calculation spaces.
For example, the expression 'G=a*b+c' is equivalent to t1=A*B; G=T1+C;
del t1; It will be more quickly executed as G=A*B; add(G,C,G) which is
the same as G=A*B; G+=C.
\end_layout
\begin_layout Subsection
Trigonometric functions
\end_layout
\begin_layout Standard
All trigonometric functions use radians when an angle is called for.
The ratio of degrees to radians is
\begin_inset Formula $180^{\circ}/\pi.$
\end_inset
\end_layout
\begin_layout Description
sin (
\begin_inset Formula $x$
\end_inset
[,
\begin_inset Formula $y$
\end_inset
])
\begin_inset LatexCommand index
name "sin"
\end_inset
\end_layout
\begin_layout Description
cos (
\begin_inset Formula $x$
\end_inset
[,
\begin_inset Formula $y$
\end_inset
])
\begin_inset LatexCommand index
name "cos"
\end_inset
\end_layout
\begin_layout Description
tan (
\begin_inset Formula $x$
\end_inset
[,
\begin_inset Formula $y$
\end_inset
])
\begin_inset LatexCommand index
name "tan"
\end_inset
\end_layout
\begin_layout Description
\InsetSpace ~
The standard trignometric functions.
\begin_inset Formula $y=\sin\left(x\right),$
\end_inset
\begin_inset Formula $y=\cos\left(x\right),$
\end_inset
and
\begin_inset Formula $y=\tan\left(x\right).$
\end_inset
\end_layout
\begin_layout Description
arcsin (
\begin_inset Formula $x$
\end_inset
[,
\begin_inset Formula $y$
\end_inset
])
\begin_inset LatexCommand index
name "arcsin"
\end_inset
\end_layout
\begin_layout Description
arccos (
\begin_inset Formula $x$
\end_inset
[,
\begin_inset Formula $y$
\end_inset
])
\begin_inset LatexCommand index
name "arccos"
\end_inset
\end_layout
\begin_layout Description
arctan (
\begin_inset Formula $x$
\end_inset
[,
\begin_inset Formula $y$
\end_inset
])
\begin_inset LatexCommand index
name "arctan"
\end_inset
\end_layout
\begin_layout Description
\InsetSpace ~
The inverse trigonometric functions:
\begin_inset Formula $y=\sin^{-1}\left(x\right),$
\end_inset
\begin_inset Formula $y=\cos^{-1}\left(x\right)$
\end_inset
,
\begin_inset Formula $y=\tan^{-1}\left(x\right).$
\end_inset
These return the value of
\begin_inset Formula $y$
\end_inset
(in radians) such that
\begin_inset Formula $\sin\left(y\right)=x$
\end_inset
with
\begin_inset Formula $y\in\left[-\frac{\pi}{2},\frac{\pi}{2}\right]$
\end_inset
;
\begin_inset Formula $\cos\left(y\right)=x$
\end_inset
with
\begin_inset Formula $y\in\left[0,\pi\right]$
\end_inset
; and
\begin_inset Formula $\tan\left(y\right)=x$
\end_inset
with
\begin_inset Formula $y\in\left[-\frac{\pi}{2},\frac{\pi}{2}\right]$
\end_inset
, respectively.
\end_layout
\begin_layout Description
arctan2 (
\begin_inset Formula $x_{1}$
\end_inset
,
\begin_inset Formula $x_{2}$
\end_inset
[,
\begin_inset Formula $y$
\end_inset
])
\begin_inset LatexCommand index
name "arctan2"
\end_inset
\end_layout
\begin_layout Description
\InsetSpace ~
Returns
\begin_inset Formula $\tan^{-1}\left(\frac{x_{1}}{x_{2}}\right)$
\end_inset
but takes into account the sign on
\begin_inset Formula $x_{1}$
\end_inset
and
\begin_inset Formula $x_{2}$
\end_inset
to place the angle in the correct quadrant.
The angle
\begin_inset Formula $y$
\end_inset
is returned in the full range
\begin_inset Formula $-\pi
\begin_inset Text
\begin_layout Standard
\begin_inset Formula $x_{1}$
\end_inset
\end_layout
\end_inset
|
\begin_inset Text
\begin_layout Standard
\begin_inset Formula $x_{2}$
\end_inset
\end_layout
\end_inset
|
\begin_inset Text
\begin_layout Standard
\begin_inset Formula $y=\textrm{arctan2}\left(x_{1},x_{2}\right)$
\end_inset
\end_layout
\end_inset
|
\begin_inset Text
\begin_layout Standard
0
\end_layout
\end_inset
|
\begin_inset Text
\begin_layout Standard
1
\end_layout
\end_inset
|
\begin_inset Text
\begin_layout Standard
0
\end_layout
\end_inset
|
\begin_inset Text
\begin_layout Standard
1
\end_layout
\end_inset
|
\begin_inset Text
\begin_layout Standard
0
\end_layout
\end_inset
|
\begin_inset Text
\begin_layout Standard
\begin_inset Formula $\frac{\pi}{2}$
\end_inset
\end_layout
\end_inset
|
\begin_inset Text
\begin_layout Standard
0
\end_layout
\end_inset
|
\begin_inset Text
\begin_layout Standard
-1
\end_layout
\end_inset
|
\begin_inset Text
\begin_layout Standard
\begin_inset Formula $\pi$
\end_inset
\end_layout
\end_inset
|
\begin_inset Text
\begin_layout Standard
-1
\end_layout
\end_inset
|
\begin_inset Text
\begin_layout Standard
0
\end_layout
\end_inset
|
\begin_inset Text
\begin_layout Standard
\begin_inset Formula $-\frac{\pi}{2}$
\end_inset
\end_layout
\end_inset
|
\end_inset
\end_layout
\begin_layout Description
hypot (
\begin_inset Formula $x_{1}$
\end_inset
,
\begin_inset Formula $x_{2}$
\end_inset
[,
\begin_inset Formula $y$
\end_inset
])
\begin_inset LatexCommand index
name "hypot"
\end_inset
\end_layout
\begin_layout Description
\InsetSpace ~
Returns
\begin_inset Formula $y=\sqrt{x_{1}^{2}+x_{2}^{2}}.$
\end_inset
Given a complex number in cartesian form, arctan2 and hypot can be used
to compute phase and magnitude, quickly.
\end_layout
\begin_layout Description
sinh (
\begin_inset Formula $x$
\end_inset
[,
\begin_inset Formula $y$
\end_inset
])
\begin_inset LatexCommand index
name "sinh"
\end_inset
\end_layout
\begin_layout Description
\InsetSpace ~
Computes
\begin_inset Formula $y=\sinh\left(x\right)$
\end_inset
which is defined as
\begin_inset Formula $\frac{1}{2}\left(e^{x}-e^{-x}\right).$
\end_inset
\end_layout
\begin_layout Description
cosh (
\begin_inset Formula $x$
\end_inset
[,
\begin_inset Formula $y$
\end_inset
])
\begin_inset LatexCommand index
name "cosh"
\end_inset
\end_layout
\begin_layout Description
\InsetSpace ~
Computes
\begin_inset Formula $y=\cosh\left(x\right)$
\end_inset
which is defined as
\begin_inset Formula $\frac{1}{2}\left(e^{x}+e^{-x}\right).$
\end_inset
\end_layout
\begin_layout Description
tanh (
\begin_inset Formula $x$
\end_inset
[,
\begin_inset Formula $y$
\end_inset
])
\begin_inset LatexCommand index
name "tanh"
\end_inset
\end_layout
\begin_layout Description
\InsetSpace ~
Computes
\begin_inset Formula $y=\tanh\left(x\right)$
\end_inset
which is defined as
\begin_inset Formula $\left(e^{x}-e^{-x}\right)/\left(e^{x}+e^{-x}\right).$
\end_inset
\end_layout
\begin_layout Description
arcsinh (
\begin_inset Formula $x$
\end_inset
[,
\begin_inset Formula $y$
\end_inset
])
\begin_inset LatexCommand index
name "arcsinh"
\end_inset
\end_layout
\begin_layout Description
arccosh (
\begin_inset Formula $x$
\end_inset
[,
\begin_inset Formula $y$
\end_inset
])
\begin_inset LatexCommand index
name "arccosh"
\end_inset
\end_layout
\begin_layout Description
arctanh (
\begin_inset Formula $x$
\end_inset
[,
\begin_inset Formula $y$
\end_inset
])
\begin_inset LatexCommand index
name "arctanh"
\end_inset
\end_layout
\begin_layout Description
\InsetSpace ~
These compute the inverse hyperpolic functions.
\begin_inset Formula $y=\textrm{arc}func\left(x\right)$
\end_inset
is the (principal) value of
\begin_inset Formula $y$
\end_inset
such that
\begin_inset Formula $func\left(y\right)=x.$
\end_inset
\end_layout
\begin_layout Subsection
Bit-twiddling functions
\end_layout
\begin_layout Standard
These function all need integer arguments and they maniuplate the bit-pattern
of those arguments.
\end_layout
\begin_layout Description
bitwise_and (
\begin_inset Formula $x_{1}$
\end_inset
,
\begin_inset Formula $x_{2}$
\end_inset
[,
\begin_inset Formula $y$
\end_inset
])
\begin_inset LatexCommand index
name "bitwise\\_and"
\end_inset
\end_layout
\begin_layout Description
\InsetSpace ~
Each bit in
\begin_inset Formula $y$
\end_inset
is the result of a bit-wise 'and' operation on the corresponding bits in
\begin_inset Formula $x_{1}$
\end_inset
and
\begin_inset Formula $x_{2}$
\end_inset
.
Called to implement
\family typewriter
x1&x2
\family default
for arrays.
\end_layout
\begin_layout Description
bitwise_or (
\begin_inset Formula $x_{1}$
\end_inset
,
\begin_inset Formula $x_{2}$
\end_inset
[,
\begin_inset Formula $y$
\end_inset
])
\begin_inset LatexCommand index
name "bitwise\\_or"
\end_inset
\end_layout
\begin_layout Description
\InsetSpace ~
Each bit in
\begin_inset Formula $y$
\end_inset
is the result of a bit-wise 'or' operation on the corresponding bits in
\begin_inset Formula $x_{1}$
\end_inset
and
\begin_inset Formula $x_{2}$
\end_inset
.
Called to implement
\family typewriter
x1|x2
\family default
for arrays.
\end_layout
\begin_layout Description
bitwise_xor (
\begin_inset Formula $x_{1}$
\end_inset
,
\begin_inset Formula $x_{2}$
\end_inset
[,
\begin_inset Formula $y$
\end_inset
])
\begin_inset LatexCommand index
name "bitwise\\_xor"
\end_inset
\end_layout
\begin_layout Description
\InsetSpace ~
Each bit in
\begin_inset Formula $y$
\end_inset
is the result of a bit-wise 'xor' operation on the corresponding bits in
\begin_inset Formula $x_{1}$
\end_inset
and
\begin_inset Formula $x_{2}$
\end_inset
.
An xor operation sets the output to 1 if one and only one of the input
bits is 1.
Called to implement
\family typewriter
x1^x2
\family default
for arrays.
Using the bitwise_xor operation and the optional output argument you can
swap the values of two integer arrays of equivalent types without using
temporary arrays.
\end_layout
\begin_layout MyCode
>>> a=arange(10)
\newline
>>> b=arange(10,20)
\newline
>>> bitwise_xor(a,b,a); bitwise_xor(a,b,b);
\newline
>>
> bitwise_xor(a,b,a)
\newline
array([10, 11, 12, 13, 14, 15, 16, 17, 18, 19])
\newline
>>> print
a; print b
\newline
[10 11 12 13 14 15 16 17 18 19]
\newline
[0 1 2 3 4 5 6 7 8 9]
\end_layout
\begin_layout Description
invert (
\begin_inset Formula $x$
\end_inset
, [,
\begin_inset Formula $y$
\end_inset
])
\begin_inset LatexCommand index
name "invert"
\end_inset
\end_layout
\begin_layout Description
\InsetSpace ~
Each bit in
\begin_inset Formula $y$
\end_inset
is the opposite of the corresponding bit in
\begin_inset Formula $x$
\end_inset
.
Called to implement
\family typewriter
~x
\family default
for arrays.
\end_layout
\begin_layout Description
left_shift (
\begin_inset Formula $x_{1}$
\end_inset
,
\begin_inset Formula $x_{2}$
\end_inset
[,
\begin_inset Formula $y$
\end_inset
])
\begin_inset LatexCommand index
name "left\\_shift"
\end_inset
\end_layout
\begin_layout Description
\InsetSpace ~
Shifts the bits of
\begin_inset Formula $x_{1}$
\end_inset
to the left by
\begin_inset Formula $x_{2}$
\end_inset
.
Called to implement
\family typewriter
x1<>x2
\family default
for arrays.
Absent overflow, the result is equal to
\begin_inset Formula $y=x_{1}2^{-x_{2}}$
\end_inset
.
\end_layout
\begin_layout Subsection
Comparison functions
\end_layout
\begin_layout Standard
All of these functions (except maximum, minimum, and sign) return Boolean
arrays.
\end_layout
\begin_layout Description
greater (
\begin_inset Formula $x_{1}$
\end_inset
,
\begin_inset Formula $x_{2}$
\end_inset
[,
\begin_inset Formula $y$
\end_inset
])
\begin_inset LatexCommand index
name "greater"
\end_inset
\end_layout
\begin_layout Description
greater_equal (
\begin_inset Formula $x_{1}$
\end_inset
,
\begin_inset Formula $x_{2}$
\end_inset
[,
\begin_inset Formula $y$
\end_inset
])
\begin_inset LatexCommand index
name "greater\\_equal"
\end_inset
\end_layout
\begin_layout Description
less (
\begin_inset Formula $x_{1}$
\end_inset
,
\begin_inset Formula $x_{2}$
\end_inset
[,
\begin_inset Formula $y$
\end_inset
])
\begin_inset LatexCommand index
name "less"
\end_inset
\end_layout
\begin_layout Description
less_equal (
\begin_inset Formula $x_{1}$
\end_inset
,
\begin_inset Formula $x_{2}$
\end_inset
[,
\begin_inset Formula $y$
\end_inset
])
\begin_inset LatexCommand index
name "less\\_equal"
\end_inset
\end_layout
\begin_layout Description
not_equal (
\begin_inset Formula $x_{1}$
\end_inset
,
\begin_inset Formula $x_{2}$
\end_inset
[,
\begin_inset Formula $y$
\end_inset
])
\begin_inset LatexCommand index
name "not\\_equal"
\end_inset
\end_layout
\begin_layout Description
equal (
\begin_inset Formula $x_{1}$
\end_inset
,
\begin_inset Formula $x_{2}$
\end_inset
[,
\begin_inset Formula $y$
\end_inset
])
\begin_inset LatexCommand index
name "equal"
\end_inset
\end_layout
\begin_layout Description
\InsetSpace ~
These functions are called to implement
\family typewriter
x1>x2
\family default
,
\family typewriter
x1>=x2
\family default
,
\family typewriter
x1x2
\family default
), and
\family typewriter
x1==x2
\family default
, respectively, for arrays.
\end_layout
\begin_layout Description
\InsetSpace ~
The fact that these functions return Boolean arrays make them very useful
in combination with advanced array indexing.
Thus, for example, arr[arr>10] = 10 clips large values to 10.
Used in conjunction with bitwise operators quite complicated expressions
are possible.
For example, arr[~((arr<10)&(arr>5))] = 0 clips all values outside of the
range
\begin_inset Formula $\left(5,10\right)$
\end_inset
to 0.
\end_layout
\begin_layout Warning
Do not use the Python keywords
\family typewriter
and
\family default
and
\family typewriter
or
\family default
to combine logical array expressions.
These keywords will test the truth value of the entire array (not element-by-el
ement as you might expect).
Use the bitwise operators: & and | instead.
\end_layout
\begin_layout Description
logical_and (
\begin_inset Formula $x_{1}$
\end_inset
,
\begin_inset Formula $x_{2}$
\end_inset
[,
\begin_inset Formula $y$
\end_inset
])
\begin_inset LatexCommand index
name "logical\\_and"
\end_inset
\end_layout
\begin_layout Description
\InsetSpace ~
The output is the truth value of
\begin_inset Formula $x_{1}$
\end_inset
\series bold
and
\series default
\begin_inset Formula $x_{2}$
\end_inset
.
Numbers equal to 0 are considered False.
Nonzero numbers are True.
\end_layout
\begin_layout Description
logical_or (
\begin_inset Formula $x_{1}$
\end_inset
,
\begin_inset Formula $x_{2}$
\end_inset
[,
\begin_inset Formula $y$
\end_inset
])
\begin_inset LatexCommand index
name "logical\\_or"
\end_inset
\end_layout
\begin_layout Description
\InsetSpace ~
The output,
\begin_inset Formula $y$
\end_inset
, is the truth value of
\begin_inset Formula $x_{1}$
\end_inset
\series bold
or
\begin_inset Formula $x_{2}$
\end_inset
\series default
.
\end_layout
\begin_layout Description
logical_xor (
\begin_inset Formula $x_{1}$
\end_inset
,
\begin_inset Formula $x_{2}$
\end_inset
[,
\begin_inset Formula $y$
\end_inset
])
\begin_inset LatexCommand index
name "logical\\_xor"
\end_inset
\end_layout
\begin_layout Description
\InsetSpace ~
The output,
\begin_inset Formula $y$
\end_inset
, is the truth value of
\begin_inset Formula $x_{1}$
\end_inset
\series bold
xor
\begin_inset Formula $x_{2}$
\end_inset
\series default
, which is the same as (
\begin_inset Formula $x_{1}$
\end_inset
and not
\begin_inset Formula $x_{2}$
\end_inset
) or (not
\begin_inset Formula $x_{1}$
\end_inset
and
\begin_inset Formula $x_{2}$
\end_inset
).
\end_layout
\begin_layout Description
logical_not (
\begin_inset Formula $x$
\end_inset
[,
\begin_inset Formula $y$
\end_inset
])
\begin_inset LatexCommand index
name "logical\\_not"
\end_inset
\end_layout
\begin_layout Description
\InsetSpace ~
The output,
\begin_inset Formula $y$
\end_inset
is the truth value of
\series bold
not
\series default
\begin_inset Formula $x$
\end_inset
.
\end_layout
\begin_layout Warning
The Bitwise operators (& and |) are the proper way to combine element-by-element
array comparisons.
Be sure to understand the operator precedence: (a>2) & (a<5) is the proper
syntax because a>2 & a<5 will result in an error due to the fact that 2
& a is evaluated first.
\end_layout
\begin_layout Description
maximum (
\begin_inset Formula $x_{1}$
\end_inset
,
\begin_inset Formula $x_{2}$
\end_inset
[,
\begin_inset Formula $y$
\end_inset
])
\begin_inset LatexCommand index
name "maximum"
\end_inset
\end_layout
\begin_layout Description
\InsetSpace ~
The output,
\begin_inset Formula $y$
\end_inset
, is the larger of
\begin_inset Formula $x_{1}$
\end_inset
and
\begin_inset Formula $x_{2}$
\end_inset
.
\end_layout
\begin_layout MyCode
>>> maximum([1,0,5,10],[3,2,4,5])
\newline
array([ 3, 2, 5, 10])
\newline
>>> max([1,0,5,10],[3,2,
4,5])
\newline
[3, 2, 4, 5]
\end_layout
\begin_layout Tip
The Python function max() will find the maximum over a one-dimensional array,
but it will do so using a slower sequence interface.
The reduce method of the maximum ufunc is much faster.
Also, the max() method will not give answers you might expect for arrays
with greater than one dimension.
The reduce method of minimum also allows you to compute a total minimum
over an array.
\end_layout
\begin_layout Description
minimum (
\begin_inset Formula $x_{1}$
\end_inset
,
\begin_inset Formula $x_{2}$
\end_inset
[,
\begin_inset Formula $y$
\end_inset
])
\begin_inset LatexCommand index
name "minimum"
\end_inset
\end_layout
\begin_layout Description
\InsetSpace ~
The output,
\begin_inset Formula $y$
\end_inset
, is the smaller of
\begin_inset Formula $x_{1}$
\end_inset
and
\begin_inset Formula $x_{2}$
\end_inset
.
\end_layout
\begin_layout MyCode
>>> minimum([1,0,5,10],[3,2,4,5])
\newline
array([1, 0, 4, 5])
\newline
>>> min([1,0,5,10],[3,2,4,5]
)
\newline
[1, 0, 5, 10]
\end_layout
\begin_layout Warning
the behavior of maximum(a,b) is than that of max(a,b).
As a ufunc, maximum(a,b) performs an element-by-element comparison of a
and b and chooses each element of the result according to which element
in the two arrays is larger.
In contrast, max(a,b) treats the objects a and b as a whole, looks at the
(total) truth value of a>b and uses it to return either a or b (as a whole).
A similar difference exists between minimum(a,b) and min(a,b).
\end_layout
\begin_layout Subsection
Floating functions
\end_layout
\begin_layout Standard
Recall that all of these functions work element-by-element over an array,
returning an array output.
The description details only a single operation.
\end_layout
\begin_layout Description
isreal (
\begin_inset Formula $x$
\end_inset
)
\begin_inset LatexCommand index
name "isreal"
\end_inset
\end_layout
\begin_layout Description
\InsetSpace ~
True if
\begin_inset Formula $x$
\end_inset
has an imaginary part that is 0.
\end_layout
\begin_layout Description
iscomplex (
\begin_inset Formula $x$
\end_inset
)
\begin_inset LatexCommand index
name "iscomplex"
\end_inset
\end_layout
\begin_layout Description
\InsetSpace ~
True if
\begin_inset Formula $x$
\end_inset
has an imaginary part that is non-zero.
\end_layout
\begin_layout Description
isfinite (
\begin_inset Formula $x$
\end_inset
)
\begin_inset LatexCommand index
name "isfinite"
\end_inset
\end_layout
\begin_layout Description
\InsetSpace ~
True if
\begin_inset Formula $x$
\end_inset
is a finite floating point number (not a NaN or an Inf).
\end_layout
\begin_layout Description
isinf (
\begin_inset Formula $x$
\end_inset
)
\begin_inset LatexCommand index
name "isinf"
\end_inset
\end_layout
\begin_layout Description
\InsetSpace ~
True if
\begin_inset Formula $x$
\end_inset
is
\begin_inset Formula $\pm\infty$
\end_inset
.
\end_layout
\begin_layout Description
isnan (
\begin_inset Formula $x$
\end_inset
)
\begin_inset LatexCommand index
name "isnan"
\end_inset
\end_layout
\begin_layout Description
\InsetSpace ~
True if
\begin_inset Formula $x$
\end_inset
is Not-a-Number.
This represents invalid results.
When a NaN is created, the invalid flag is set.
If you set the error mode of invalid to 'warn', 'raise', or 'call', then
the appropriate action will be performed on NaN creation.
\end_layout
\begin_layout Description
signbit (
\begin_inset Formula $x$
\end_inset
)
\begin_inset LatexCommand index
name "signbit"
\end_inset
\end_layout
\begin_layout Description
\InsetSpace ~
True where the sign bit of the floating point number is set.
This should correspond to
\begin_inset Formula $x>0$
\end_inset
when
\begin_inset Formula $x$
\end_inset
is a finite number.
When,
\begin_inset Formula $x$
\end_inset
is NaN or infinite, then this tests the actual signbit.
\end_layout
\begin_layout Description
modf (
\begin_inset Formula $x$
\end_inset
[,
\begin_inset Formula $y_{1}$
\end_inset
,
\begin_inset Formula $y_{2}$
\end_inset
])
\begin_inset LatexCommand index
name "modf"
\end_inset
\end_layout
\begin_layout Description
\InsetSpace ~
Breaks up the floating point value
\begin_inset Formula $x$
\end_inset
into its fractional,
\begin_inset Formula $y_{1}$
\end_inset
, and integral,
\begin_inset Formula $y_{2}$
\end_inset
, parts.
Thus,
\begin_inset Formula $x=y_{1}+y_{2}$
\end_inset
with
\family typewriter
floor(y2)==y2
\family default
.
\end_layout
\begin_layout Description
ldexp (
\begin_inset Formula $x$
\end_inset
,
\begin_inset Formula $n$
\end_inset
[,
\begin_inset Formula $y$
\end_inset
])
\begin_inset LatexCommand index
name "ldexp"
\end_inset
\end_layout
\begin_layout Description
\InsetSpace ~
Fast multiply of a floating point number by an integral power of 2:
\begin_inset Formula $y=2^{n}x.$
\end_inset
\end_layout
\begin_layout Description
frexp (
\begin_inset Formula $x$
\end_inset
[,
\begin_inset Formula $y$
\end_inset
,
\begin_inset Formula $n$
\end_inset
])
\begin_inset LatexCommand index
name "frexp"
\end_inset
\end_layout
\begin_layout Description
\InsetSpace ~
Breaks up the floating point value
\begin_inset Formula $x$
\end_inset
into a normalized fraction,
\begin_inset Formula $y$
\end_inset
and an exponent,
\begin_inset Formula $n$
\end_inset
which corresponds to how the value is represented in the computer.
The results are such that
\begin_inset Formula $x=y2^{n}.$
\end_inset
Effectively, the inverse of ldexp.
\end_layout
\begin_layout Description
fmod (
\begin_inset Formula $x_{1}$
\end_inset
,
\begin_inset Formula $x_{2}$
\end_inset
[,
\begin_inset Formula $y$
\end_inset
])
\begin_inset LatexCommand index
name "fmod"
\end_inset
\end_layout
\begin_layout Description
\InsetSpace ~
Computes the remainder of dividing
\begin_inset Formula $x_{1}$
\end_inset
by
\begin_inset Formula $x_{2}$
\end_inset
.
The result,
\begin_inset Formula $y$
\end_inset
, is
\begin_inset Formula $x_{1}-nx_{2}$
\end_inset
where
\begin_inset Formula $n$
\end_inset
is the quotient (rounded towards zero to an integer) of
\begin_inset Formula $x_{1}/x_{2}.$
\end_inset
\end_layout
\begin_layout Description
floor (
\begin_inset Formula $x$
\end_inset
[,
\begin_inset Formula $y$
\end_inset
])
\begin_inset LatexCommand index
name "floor"
\end_inset
\end_layout
\begin_layout Description
\InsetSpace ~
Return
\begin_inset Formula $y=\left\lfloor x\right\rfloor $
\end_inset
where
\begin_inset Formula $y$
\end_inset
is the nearest integer smaller-than or equal to
\begin_inset Formula $x.$
\end_inset
Thus,
\begin_inset Formula $ $
\end_inset
\begin_inset Formula $\left\lfloor x\right\rfloor \leq x<\left\lfloor x\right\rfloor +1$
\end_inset
.
\end_layout
\begin_layout Description
ceil (
\begin_inset Formula $x$
\end_inset
[,
\begin_inset Formula $y$
\end_inset
])
\begin_inset LatexCommand index
name "ceil"
\end_inset
\end_layout
\begin_layout Description
\InsetSpace ~
Return
\begin_inset Formula $y=\left\lceil x\right\rceil $
\end_inset
where
\begin_inset Formula $y$
\end_inset
is the nearest integer greater-than or equal to
\begin_inset Formula $x$
\end_inset
.
Thus,
\begin_inset Formula $x\leq\left\lceil x\right\rceil
\begin_inset Text
\begin_layout Standard
Family
\end_layout
\end_inset
|
\begin_inset Text
\begin_layout Standard
Functions
\end_layout
\end_inset
|
\begin_inset Text
\begin_layout Standard
Fourier Transforms
\end_layout
\end_inset
|
\begin_inset Text
\begin_layout Standard
fft, ifft, fft2, ifft2, fftn, ifftn
\end_layout
\end_inset
|
\begin_inset Text
\begin_layout Standard
Linear Algebra
\end_layout
\end_inset
|
\begin_inset Text
\begin_layout Standard
norm, det, inv, pinv, solve, eig, eigh, eigvals, eigvalsh, lstsq, cholesky,
svd
\end_layout
\end_inset
|
\begin_inset Text
\begin_layout Standard
Special Functions
\end_layout
\end_inset
|
\begin_inset Text
\begin_layout Standard
i0
\end_layout
\end_inset
|
\end_inset
\end_layout
\end_inset
\end_layout
\begin_layout Section
Linear Algebra (
\family typewriter
linalg
\family default
)
\end_layout
\begin_layout Standard
\begin_inset LatexCommand index
name "linalg|("
\end_inset
These functions are in the numpy.linalg sub-package.
\end_layout
\begin_layout Description
inv (A)
\end_layout
\begin_layout Description
\InsetSpace ~
Return the (matrix) inverse of the 2-d array A.
The result, X, is such that dot(A,X) is equal to eye(*A.shape) (to within
machine precision).
\end_layout
\begin_layout Description
solve (A,b)
\end_layout
\begin_layout Description
\InsetSpace ~
Find the solution to the linear equation
\begin_inset Formula $\mathbf{Ax}=\mathbf{b}$
\end_inset
, where
\begin_inset Formula $A$
\end_inset
is a 2-d array and
\begin_inset Formula $b$
\end_inset
is a 1-d or 2-d array.
\end_layout
\begin_layout Description
tensorsolve (A, b, axes=None)
\end_layout
\begin_layout Description
\InsetSpace ~
Find the solution,
\begin_inset Formula $x_{kl}$
\end_inset
, to the multi-index linear equation
\begin_inset Formula \[
\sum_{kl}A_{ijkl}x_{kl}=b_{ij}.\]
\end_inset
The axes argument specifies which dimensions of
\begin_inset Formula $A$
\end_inset
are summed over.
If it is None, then the last A.ndim - b.ndim dimensions are summed over.
The result, therefore, has dimension x.ndim = A.ndim-b.ndim.
\end_layout
\begin_layout Description
tensorinv (A, ind=2)
\end_layout
\begin_layout Description
\InsetSpace ~
Find the tensor inverse of
\begin_inset Formula $A$
\end_inset
, defined to be the tensor such that tensordot (Ainv, A) is an identity
operator.
\end_layout
\begin_layout Description
cholesky (A)
\end_layout
\begin_layout Description
\InsetSpace ~
Return,
\begin_inset Formula $\mathbf{L}$
\end_inset
, the Cholesky decomposition of
\begin_inset Formula $\mathbf{A}$
\end_inset
.
Cholesky decomposition is applicable to a Hermitian, positive definite
matrices.
When
\begin_inset Formula $\mathbf{A}=\mathbf{A}^{H}$
\end_inset
and
\begin_inset Formula $\mathbf{x}^{H}\mathbf{Ax}\geq0$
\end_inset
for all
\begin_inset Formula $\mathbf{x}$
\end_inset
, then decompositions of
\begin_inset Formula $\mathbf{A}$
\end_inset
can be found so that
\begin_inset Formula $\mathbf{A}=\mathbf{LL}^{H}$
\end_inset
, where
\begin_inset Formula $\mathbf{L}$
\end_inset
is lower-triangular.
\end_layout
\begin_layout Description
eigvals (A)
\end_layout
\begin_layout Description
\InsetSpace ~
Return all solutions (
\begin_inset Formula $\lambda$
\end_inset
) to the equation
\begin_inset Formula $\mathbf{Ax}=\lambda\mathbf{x}$
\end_inset
.
\end_layout
\begin_layout Description
eig (A)
\end_layout
\begin_layout Description
\InsetSpace ~
Return all solutions
\begin_inset Formula $\left(\lambda,\mathbf{x}\right)$
\end_inset
to the equation
\begin_inset Formula $\mathbf{Ax}=\lambda\mathbf{x}$
\end_inset
.
The first element of the return tuple contains all the eigenvalues.
The second element of the return tuple contains the eigenvectors in the
columns (x[:,i] is the ith eigenvector).
\end_layout
\begin_layout Description
eigvalsh (U)
\end_layout
\begin_layout Description
eigh (U)
\end_layout
\begin_layout Description
\InsetSpace ~
These functions are identical to eigvals and eig except they only work
with Hermitian matrices where
\begin_inset Formula $\mathbf{U}^{H}=\mathbf{U}$
\end_inset
(only the lower-triangular part of the array is used).
\end_layout
\begin_layout Description
svd (A)
\end_layout
\begin_layout Description
\InsetSpace ~
Compute the singular value decomposition of the 2-d array
\begin_inset Formula $\mathbf{A}$
\end_inset
.
Every
\begin_inset Formula $m\times n$
\end_inset
matrix can be decomposed into a pair of unitary matrices,
\begin_inset Formula $\mathbf{U}=\mathbf{U}^{H}$
\end_inset
(
\begin_inset Formula $m\times m$
\end_inset
) and
\begin_inset Formula $\mathbf{V}=\mathbf{V}^{H}$
\end_inset
(
\begin_inset Formula $n\times n$
\end_inset
) and an
\begin_inset Formula $m\times n$
\end_inset
\begin_inset Quotes eld
\end_inset
diagonal
\begin_inset Quotes erd
\end_inset
matrix
\begin_inset Formula $\boldsymbol{\Sigma}$
\end_inset
, such that
\begin_inset Formula $\mathbf{A}=\mathbf{U\boldsymbol{\Sigma}}\mathbf{V}^{H}$
\end_inset
.
The only non-zero portion of
\begin_inset Formula $\boldsymbol{\Sigma}$
\end_inset
is the upper
\begin_inset Formula $r\times r$
\end_inset
block where
\begin_inset Formula $r=\min\left(m,n\right)$
\end_inset
.
The svd function returns three arrays as a tuple: (
\begin_inset Formula $\mathbf{U}$
\end_inset
,
\begin_inset Formula $\boldsymbol{\sigma}$
\end_inset
,
\begin_inset Formula $\mathbf{V}^{H}$
\end_inset
).
The singular values are returned in the 1-d array
\begin_inset Formula $\boldsymbol{\sigma}$
\end_inset
.
If needed, the array
\begin_inset Formula $\boldsymbol{\Sigma}$
\end_inset
can be found (if really needed) using the command diag(
\begin_inset Formula $\boldsymbol{\sigma}$
\end_inset
) which creates the
\begin_inset Formula $r\times r$
\end_inset
diagonal block and then inserting this into a zeros matrix:
\end_layout
\begin_layout MyCode
>>> A = random.rand(3,5)
\newline
>>> from numpy.dual import svd; U,s,Vh = svd(A)
\newline
>>>
r=min(*A.shape); Sig = zeros_like(A);
\newline
>>> Sig[:r,:r] = diag(s); print Sig
\newline
[[
2.1634 0.
0.
0.
0.
]
\newline
[ 0.
0.7076 0.
0.
0.
]
\newline
[ 0.
0.
0.2098 0.
0.
]]
\end_layout
\begin_layout Description
pinv (A, rcond=
\begin_inset Formula $10^{-10}$
\end_inset
)
\end_layout
\begin_layout Description
\InsetSpace ~
Return the generalized, pseudo inverse, of
\begin_inset Formula $A$
\end_inset
.
For invertible matrices, this is the same as the inverse.
\end_layout
\begin_layout Description
det (A)
\end_layout
\begin_layout Description
\InsetSpace ~
Return the determinant of the array.
The determinant of an array is the product of its singular values.
\end_layout
\begin_layout Description
lstsq (A, b, rcond=
\begin_inset Formula $10^{-10}$
\end_inset
)
\end_layout
\begin_layout Description
\InsetSpace ~
Return (x, resids, rank, s) where x minimizes resids=
\begin_inset Formula $\left\Vert \mathbf{Ax}-\mathbf{b}\right\Vert _{2}$
\end_inset
.
The output rank is the rank of A and s is the singular values of a in descendin
g order.
Singular values less than s[0]*rcond are treated as 0.
If the rank of A is less than the number of columns of A or greater than
the number of rows, resids will be returned as an empty array.
\begin_inset LatexCommand index
name "linalg|)"
\end_inset
\end_layout
\begin_layout Section
Discrete Fourier Transforms (
\family typewriter
fft
\family default
)
\end_layout
\begin_layout Standard
\begin_inset LatexCommand index
name "fft|("
\end_inset
All of the algorithms here are most efficient if the length of the data
is a power of 2 (or decomposable into low prime factors).
\end_layout
\begin_layout Description
fft (x, n=None, axis=-1)
\end_layout
\begin_layout Description
\InsetSpace ~
Return, X, the N-point Discrete Fourier Transform (DFT) of x along the
given axis using a fast algorithm.
If N is larger than x.shape[axis], then x will be zero-padded.
If N is smaller than x.shape[axis], then the first N items will be used.
The result is computed for
\begin_inset Formula $k=0\ldots n-1$
\end_inset
from the formula:
\end_layout
\begin_layout Standard
\begin_inset Formula \[
X\left[k\right]=\sum_{m=0}^{n-1}x[m]\exp\left(-j\frac{2\pi km}{n}\right).\]
\end_inset
\end_layout
\begin_layout Tip
The fft returns values for
\begin_inset Formula $k=0\ldots N-1$
\end_inset
.
Because
\begin_inset Formula $X\left[N-k\right]=X[-k]$
\end_inset
in the FFT formula, larger values of k correspond also to negative frequencies.
\end_layout
\begin_layout Description
ifft (X, n=None, axis=-1)
\end_layout
\begin_layout Description
\InsetSpace ~
Return the inverse of the fft so that (ifft(fft(a)) == a within numerical
precision.
The order of frequencies must be the same as returned by fft.
The result is computed (using a fast algorithm) for
\begin_inset Formula $m=0\ldots n-1$
\end_inset
from the formula:
\end_layout
\begin_layout Standard
\begin_inset Formula \[
x\left[m\right]=\frac{1}{n}\sum_{k=0}^{n-1}X\left[k\right]\exp\left(j\frac{2\pi km}{n}\right).\]
\end_inset
\end_layout
\begin_layout Standard
Sometimes having the
\begin_inset Quotes eld
\end_inset
negative
\begin_inset Quotes erd
\end_inset
frequencies at the end of the output returned by fft can be a little confusing.
There are two ways to deal with this confusion.
In my opinion, the most useful way is to get a collection of DFT sample
frequencies and use them to keep track of where each frequency is.
The function
\family typewriter
fftfreq
\family default
provides these sample frequencies.
Making an x-y plot, where the sample frequencies are along the
\begin_inset Quotes eld
\end_inset
x
\begin_inset Quotes erd
\end_inset
-axis and the result of the DFT is along the
\begin_inset Quotes eld
\end_inset
y
\begin_inset Quotes erd
\end_inset
-axis provides a useful visualization with the zero-frequency at the center
of the plot.
The advantage of this approach is that your data is still in proper order
for using the
\family typewriter
ifft
\family default
function.
Some people, however, prefer to simply swap one-half of the output with
the other.
This is exactly what the function
\family typewriter
fftshift
\family default
does.
Of course, now the data is not in the proper order for the ifft function,
but to each his own.
\end_layout
\begin_layout Standard
The reason that the
\begin_inset Quotes eld
\end_inset
negative
\begin_inset Quotes erd
\end_inset
frequencies are in the upper part of the return signal was given in the
description of the DFT.
The reason is that the output of the DFT is just one period of a periodic
function (with period
\begin_inset Formula $n$
\end_inset
).
The traditional output of the FFT algorithm is to provide the portion of
the function from from
\begin_inset Formula $k=0$
\end_inset
to
\begin_inset Formula $k=n-1$
\end_inset
.
\end_layout
\begin_layout Description
fftshift (x, axes=None)
\end_layout
\begin_layout Description
\InsetSpace ~
Shift zero-frequency component to the center of the spectrum.
This function swaps half-spaces for all axes listed (defaults to all of
them).
\end_layout
\begin_layout Description
ifftshift (x, axes=None)
\end_layout
\begin_layout Description
\InsetSpace ~
Reverse the effect of the fftshift operation.
Thus, it takes zero-centered data and shifts it into the correct order
for the ifft operation.
\end_layout
\begin_layout Description
fftfreq (n, d=1.0)
\end_layout
\begin_layout Description
\InsetSpace ~
Provide the DFT sample frequencies.
The returned float array contains the frequency bins in the order returned
from the fft function.
If given,
\begin_inset Formula $d$
\end_inset
represents the sample-spacing.
The units on the frequency bins are cycles / unit.
For example, the following example computes the output frequencies (in
Hz) of the fft of
\begin_inset Formula $256$
\end_inset
samples of a voice signal sampled at 20000Hz.
\end_layout
\begin_layout MyCode
>>> from numpy.fft import fftfreq; f=fftfreq(256,d=1./20e3)
\newline
>>> print f[0],
f[1], f[2], f[128]
\newline
0.0 78.125 156.25 -10000.0
\end_layout
\begin_layout Description
fft2 (x, s=None, axes=(-2,-1))
\end_layout
\begin_layout Description
\InsetSpace ~
Return the two-dimensional fft of the array x for each 2-d array formed
by axes.
The 2-d fft is computed as
\begin_inset Formula \[
X\left[k_{0},k_{1}\right]=\sum_{m_{0}=0}^{s[0]-1}\sum_{m_{1}=0}^{s[1]-1}x\left[m_{0},m_{1}\right]\exp\left(-j\frac{2\pi k_{0}m_{0}}{s[0]}\right)\exp\left[-j\frac{2\pi k_{1}m_{1}}{s\left[1\right]}\right]\]
\end_inset
and can be realized by repeated application of the 1-d fft (first over
the axes[0] and then over axes[1]).
In other-words fft2(x,s,axes) is equivalent to fft(fft(x, s[0], axes[0]),
s[1], axes[1]).
The 2-d fft is returned for
\begin_inset Formula $k_{0}=0\ldots s[0]-1$
\end_inset
and
\begin_inset Formula $k_{1}=0\ldots s[1]-1.$
\end_inset
Symmetry (
\begin_inset Formula $X\left[s[0]-k_{0},s[1]-k_{1}\right]=X[-k_{0},-k_{1}]$
\end_inset
) ensures that higher values of
\begin_inset Formula $k_{i}$
\end_inset
correspond to negative frequencies.
\end_layout
\begin_layout Description
ifft2 (X, s=None, axes=(-2,-1))
\end_layout
\begin_layout Description
\InsetSpace ~
Return the inverse of the two-dimension fft.
Thus, ifft2(fft2(x)) == x to within numerical precision.
Note that the
\begin_inset Quotes eld
\end_inset
negative frequencies
\begin_inset Quotes erd
\end_inset
must be
\end_layout
\begin_layout Description
fftn (x, s=None, axes=None)
\end_layout
\begin_layout Description
\InsetSpace ~
Return the
\begin_inset Formula $N$
\end_inset
-dimensional fft of x.
If s is not given, then if axes is given, then
\begin_inset Formula $N$
\end_inset
=len(axes), otherwise
\begin_inset Formula $N$
\end_inset
=x.ndim.
If s is given, then
\begin_inset Formula $N$
\end_inset
=len(s).
Results are computed using a similar formula as for the 1- and 2-d FFT
with
\begin_inset Formula $N$
\end_inset
summations.
\end_layout
\begin_layout Description
ifftn (X, s=None, axes=None)
\end_layout
\begin_layout Description
\InsetSpace ~
Return the
\begin_inset Formula $N$
\end_inset
-dimensional inverse fft of
\begin_inset Formula $X$
\end_inset
.
Note that ifftn(fftn(x)) == x to within machine precision.
\end_layout
\begin_layout Standard
The Discrete Fourier transform returns complex-valued data (even for real-valued
input).
If the data was originally real-valued, then much of the output of the
full DFT is redundant.
Notice that if
\begin_inset Formula $x\left[m\right]$
\end_inset
is real, then
\begin_inset Formula \begin{eqnarray*}
X\left[n-k\right] & = & \sum_{m=0}^{n-1}x[m]\exp\left(-j\frac{2\pi\left(n-k\right)m}{n}\right)\\
& = & \left[\sum_{m=0}^{n-1}x\left[m\right]\exp\left(-j\frac{2\pi km}{n}\right)\right]^{*}\\
& = & X^{*}\left[k\right],\end{eqnarray*}
\end_inset
where
\begin_inset Formula $a^{*}$
\end_inset
denotes the complex-conjugate of
\begin_inset Formula $a$
\end_inset
.
So, the upper half of the fft output (the negative frequencies) is determined
exactly by the lower half of the output when the input is purely real.
This kind of symmetry is called Hermitian symmetry.
The real-valued Fourier transforms described next take advantage of Hermitian
symmetry to compute only the unique outputs more quickly.
\end_layout
\begin_layout Standard
The symmetry in higher dimensions is always about the origin.
If
\begin_inset Formula $N$
\end_inset
is the number of dimensions, then:
\begin_inset Formula \[
X[n_{1}-k_{1},n_{2}-k_{2},\ldots n_{N}-k_{N}]=X^{*}\left[k_{1},k_{2},\ldots,k_{N}\right].\]
\end_inset
Thus, the data-savings remains constant at about 1/2 for higher dimensions
as well.
\end_layout
\begin_layout Description
rfft (x, n=None, axis=-1)
\end_layout
\begin_layout Description
\InsetSpace ~
Compute the first n//2+1 points of the
\begin_inset Formula $n$
\end_inset
-point discrete Fourier transform of the real valued data along the given
axis.
The returned array will be just the first half of the
\family typewriter
fft
\family default
, corresponding to positive frequencies: rfft(x) == fft(x)[:n//2+1]
\end_layout
\begin_layout Description
irfft (X, n=None, axis=-1)
\end_layout
\begin_layout Description
\InsetSpace ~
Compute the inverse
\begin_inset Formula $n$
\end_inset
-point discrete Fourier transform along the given axis using the first n//2+1
points.
To within numerical precision, irfft(rfft(x))==x.
\end_layout
\begin_layout Description
rfft2 (x, s=None, axes=(-2, -1))
\end_layout
\begin_layout Description
\InsetSpace ~
Compute only the first half-plane of the two-dimensional discrete Fourier
transform corresponding to unique values.
s[0] and
\begin_inset Formula $s[1]$
\end_inset
-point DFTs will be computed along axes[0] and axes[1] dimensions, respectively.
Requires a real array.
If
\begin_inset Formula $s$
\end_inset
is None it defaults to the shape of
\begin_inset Formula $x.$
\end_inset
The real fft will be computed along the last axis specified in axes while
a full fft will be computed in the other dimension.
\end_layout
\begin_layout Description
irfft2 (X, s=None, axes=(-2, -1))
\end_layout
\begin_layout Description
\InsetSpace ~
Compute the inverse of the 2-d DFT using only the first quadrant.
Returns a real array such that to within numerical precision irfft2(rfft2(x))==
x.
\end_layout
\begin_layout Description
rfftn (x, s=None, axes=None)
\end_layout
\begin_layout Description
\InsetSpace ~
Compute only the unique part of the
\begin_inset Formula $N$
\end_inset
-dimensional DFT from a real-valued array.
If
\begin_inset Formula $s$
\end_inset
is None it defaults to the shape of x.
If axes is not given it defaults to all the axes (-n,
\begin_inset Formula $\ldots$
\end_inset
, -1).
The length of axes provides the dimensionality of the DFT.
The unique part of the real
\begin_inset Formula $N$
\end_inset
-dimensional DFT is obtained by slicing the full fft along the last axis
specified and taking n//2+1 slices.
rfftn(x) == fft(x)[sliceobj] where sliceobj[axes[-1]] = slice(None,s[-1]//2+1,N
one).
\end_layout
\begin_layout Description
irfftn (X, s=None, axes=None)
\end_layout
\begin_layout Description
\InsetSpace ~
Compute the inverse DFT from the unique portions of the N-dimensional DFT
provided by
\family typewriter
rfftn
\family default
.
\end_layout
\begin_layout Standard
Occasionally, the situation may arise where you have complex-valued data
with Hermitian symmetry (or real-valued symmetric data).
This ensures that the Fourier transform will be real.
The two functions below can calculate it without wasting extra space for
the zero-valued imaginary entries of the Discrete Fourier transform, or
the entire signal.
\end_layout
\begin_layout Description
hfft (x, n=None, axis=-1)
\end_layout
\begin_layout Description
\InsetSpace ~
Calculate the
\begin_inset Formula $n$
\end_inset
-point real-valued Fourier transform from (the first half of Hermitian-symmetric
data, x.
\end_layout
\begin_layout Description
ihfft (X, n=None, axis=-1)
\end_layout
\begin_layout Description
\InsetSpace ~
Return (the first half-of) Hermitian-symmetric data from the real-valued
Fourier transform, X.
\begin_inset LatexCommand index
name "fft|)"
\end_inset
\end_layout
\begin_layout Section
Random Numbers (
\family typewriter
random
\family default
)
\end_layout
\begin_layout Standard
\begin_inset LatexCommand index
name "random|("
\end_inset
The random number capabilities surpass those that were available in Numeric.
The random number facilities were generously contributed by Robert Kern,
who has been a dedicated and patient help to many mailing list questioners.
Robert built the random package using Pyrex to build on top of his own
code as well as that of randomkit by Jean-Sebastien Roy as well as code
by Ivan Frohne.
The fundamental random number generator is the Mersenne Twister based on
code written by Makoto Matsumoto and Takuji Nishimura (and modified for
Python by Raymond Hettinger).
Random numbers from discrete and continuous distributions are available,
as well as some useful random-number-related utilities.
Many of the random number generators are based on algorithms published
by Luc Devroye in
\begin_inset Quotes eld
\end_inset
Non-Uniform Random Variate Generation
\begin_inset Quotes erd
\end_inset
available electronically at
\begin_inset LatexCommand htmlurl
target "http://cgm.cs.mcgill.ca/~luc/rnbookindex.html"
\end_inset
\end_layout
\begin_layout Standard
Each of the discrete and continuous random number generators take a size
keyword.
If this is None (default), then the size is determined from the additional
inputs (using ufunc-like broadcasting).
If no additional inputs are needed, or if these additional inputs are scalars,
then a single number is generated from the selected distribution.
If size is an integer, then a 1-d array of that size is generated filled
with random numbers from the selected distribution.
Finally, if size is a tuple, then an array of that shape is returned filled
with random numbers.
\end_layout
\begin_layout Standard
Many distributions take additional inputs as parameters.
These additional inputs must be broadcastable to each other (and to the
size parameter if it is not None).
The broadcasting behavior of the additional inputs is ufunc-like.
\end_layout
\begin_layout Subsection
Discrete Distributions
\end_layout
\begin_layout Standard
\begin_inset LatexCommand index
name "random!discrete|("
\end_inset
Discrete random numbers take on only a countable number of values (typically
integers).
Each distribution has associated with it a probability mass function (pmf),
\begin_inset Formula $p_{m}\left(k;\cdot\right),$
\end_inset
that is defined as the probability that the returned random number is
\begin_inset Formula $k$
\end_inset
.
The arguments after
\begin_inset Formula $k$
\end_inset
represent possible parameters to the distribution.
Thus, let
\begin_inset Formula $X\left(\cdot\right)$
\end_inset
represent the random number generator for a particular distribution.
Then,
\begin_inset Formula \[
p_{m}\left(k;\cdot\right)=\textrm{Probability}\left\{ X\left(\cdot\right)=k\right\} .\]
\end_inset
\end_layout
\begin_layout Standard
It will be useful to define the discrete indicator function,
\begin_inset Formula $I_{S}\left(k\right),$
\end_inset
where
\begin_inset Formula $S$
\end_inset
is a set of integers (often represented by an interval).
\begin_inset Formula $I_{S}\left(k\right)=1$
\end_inset
if
\begin_inset Formula $k\in S$
\end_inset
, otherwise
\begin_inset Formula $I_{S}\left(k\right)=0.$
\end_inset
This convenient notation isolates the relevance of a particular functional
form to a certain range.
Also, the formulas below make use of the following definition:
\begin_inset Formula \[
\left(\begin{array}{c}
n\\
k\end{array}\right)=\frac{n!}{k!\left(n-k\right)!}\]
\end_inset
where
\begin_inset Formula $k!=k\cdot\left(k-1\right)\cdot\cdots\cdot2\cdot1.$
\end_inset
\end_layout
\begin_layout Description
binomial (n, p, size=None)
\end_layout
\begin_layout Description
\InsetSpace ~
This random number models the number of successes in
\begin_inset Formula $n$
\end_inset
independent trials of a random experiment where the probability of success
in each experiment is
\begin_inset Formula $p$
\end_inset
.
\begin_inset Formula \[
p_{m}\left(k\right)=\left(\begin{array}{c}
n\\
k\end{array}\right)p^{k}\left(1-p\right)^{n-k}I_{\left[0,n\right]}\left(k\right).\]
\end_inset
\end_layout
\begin_layout Description
geometric (p, size=None)
\end_layout
\begin_layout Description
\InsetSpace ~
This random number models the number of (independent) attempts required
to obtain a success where the probability of success on each attempt is
\begin_inset Formula $p$
\end_inset
.
\end_layout
\begin_layout Standard
\begin_inset Formula \[
p_{m}\left(k;p\right)=\left(1-p\right)^{k-1}p\, I_{\left[1,\infty\right)}\left(k\right).\]
\end_inset
\end_layout
\begin_layout Description
hypergeometric (ngood, nbad, nsample, size=None)
\end_layout
\begin_layout Description
\InsetSpace ~
Imagine a probability theorists favorite urn filled with
\begin_inset Formula $n_{g}$
\end_inset
\begin_inset Quotes eld
\end_inset
good
\begin_inset Quotes erd
\end_inset
objects and
\begin_inset Formula $n_{b}$
\end_inset
\begin_inset Quotes eld
\end_inset
bad
\begin_inset Quotes erd
\end_inset
objects.
In other words there are two types of objects in a jar.
The hypergeometric random number models how many
\begin_inset Quotes eld
\end_inset
good
\begin_inset Quotes erd
\end_inset
objects will be present when
\begin_inset Formula $N$
\end_inset
items are taken out of the urn without replacement.
\end_layout
\begin_layout Standard
\begin_inset Formula \[
p\left(k;n_{g},n_{b},N\right)=\frac{\left(\begin{array}{c}
n_{g}\\
k\end{array}\right)\left(\begin{array}{c}
n_{b}\\
N-k\end{array}\right)}{\left(\begin{array}{c}
n_{g}+n_{b}\\
N\end{array}\right)}I_{\left[N-n_{b},\textrm{min}\left(n,N\right)\right]}\left(k\right).\]
\end_inset
\end_layout
\begin_layout Description
logseries (p, size=None)
\end_layout
\begin_layout Description
\InsetSpace ~
A random number whose pmf with terms proportional to the Taylor series
expansion of
\begin_inset Formula $\log\left(1-p\right)$
\end_inset
.
It has been used in biological studies to model the species abundance distribut
ion.
\begin_inset Formula \[
p_{m}\left(k;p\right)=-\frac{p^{k}}{k\log\left(1-p\right)}\, I_{\left[1,\infty\right)}\left(k\right).\]
\end_inset
\end_layout
\begin_layout Description
multinomial (n, pvals, size=None)
\end_layout
\begin_layout Description
\InsetSpace ~
This generator produces random vectors of length
\begin_inset Formula $N$
\end_inset
where
\begin_inset Formula $N=\textrm{len}\left(pvals\right)$
\end_inset
.
The shape of the returned array is always the shape indicated by size +
(
\begin_inset Formula $N,$
\end_inset
).
The multinomial distribution is a generalization of the binomial distribution.
This time,
\begin_inset Formula $n$
\end_inset
trials of an experiment are independently repeated but each trial results
in
\begin_inset Formula $N$
\end_inset
possible integers
\begin_inset Formula $k_{1},k_{2},\ldots,k_{N}$
\end_inset
with
\begin_inset Formula $\sum_{i=1}^{N}k_{i}=n.$
\end_inset
\begin_inset Formula \begin{eqnarray*}
p_{m}\left(k_{1},k_{2},\ldots,k_{N};\cdot\right) & = & \textrm{Probability}\left\{ X\left(\cdot\right)=\left[k_{1},k_{2},\cdots,k_{N}\right]\right\} \\
& = & \frac{n!}{k_{1}!k_{2}!\cdots k_{N}!}p_{1}^{k_{1}}p_{2}^{k_{2}}\cdots p_{N}^{k_{N}}\end{eqnarray*}
\end_inset
where
\begin_inset Formula $pvals=[p_{1},p_{2},\ldots,p_{N}].$
\end_inset
It must be true that
\begin_inset Formula $\sum_{i=1}^{N}p_{i}=1.$
\end_inset
Therefore, as long as
\begin_inset Formula $\sum_{i=1}^{N-1}p_{i}\leq1,$
\end_inset
the last entry in
\begin_inset Formula $pvals$
\end_inset
is computed as
\begin_inset Formula $1-\sum_{i=1}^{N-1}p_{i}$
\end_inset
.
\end_layout
\begin_layout Description
negative_binomial (n, p, size=None)
\end_layout
\begin_layout Description
\InsetSpace ~
Models the number of extra independent trials (beyond
\begin_inset Formula $n$
\end_inset
) required to accumulate a total of
\begin_inset Formula $n$
\end_inset
successes where the probability of success on each trial is
\begin_inset Formula $p.$
\end_inset
Equivalently, this random number models the number of failures encountered
while accumulating
\begin_inset Formula $n$
\end_inset
successes during independent trials of the experiment that succeeds with
probability,
\begin_inset Formula $p$
\end_inset
.
\end_layout
\begin_layout Standard
\begin_inset Formula \[
p_{m}\left(k;n,p\right)=\left(\begin{array}{c}
k+n-1\\
n-1\end{array}\right)p^{n}\left(1-p\right)^{k}\, I_{\left[0,\infty\right)}\left(k\right).\]
\end_inset
\end_layout
\begin_layout Description
poisson (lam=1.0, size=None)
\end_layout
\begin_layout Description
\InsetSpace ~
This random number counts the number of successes in
\begin_inset Formula $n$
\end_inset
independent experiments (where the probability of success in each experiment
is
\begin_inset Formula $p$
\end_inset
) in the limit as
\begin_inset Formula $n\rightarrow\infty$
\end_inset
and
\begin_inset Formula $p\rightarrow0$
\end_inset
gets very small such that
\begin_inset Formula $\lambda=np\geq0$
\end_inset
is a constant.
It can be used, for example, to model how many typographical errors are
on each page of a book.
\end_layout
\begin_layout Standard
\begin_inset Formula \[
p\left(k;\lambda\right)=e^{-\lambda}\frac{\lambda^{k}}{k!}\, I_{\left[0,\infty\right)}\left(k\right).\]
\end_inset
\end_layout
\begin_layout Description
zipf (a, size=None)
\end_layout
\begin_layout Description
\InsetSpace ~
The probability mass function of this random number (also called the zeta
distribution) is
\begin_inset Formula \[
p_{m}\left(k;a\right)=\frac{1}{\zeta\left(a\right)k^{a}}\, I_{\left[1,\infty\right)}\left(k\right),\]
\end_inset
where
\begin_inset Formula \[
\zeta\left(a\right)=\sum_{n=1}^{\infty}\frac{1}{n^{a}}\]
\end_inset
is the Riemann zeta function.
Zipf distributions have been shown to characterize use of words in a natural
language (like English), the popularity of library books, and even the
use of the web.
The Zipf distribution describes collections that have a few items whose
probability of selection is very high, a medium number of items whose probabili
ty of selection is medium, and a huge number of items whose probability
of selection is very low.
\begin_inset LatexCommand index
name "random!discrete|)"
\end_inset
\end_layout
\begin_layout Subsection
Continuous Distributions
\end_layout
\begin_layout Standard
\begin_inset LatexCommand index
name "random!continuous|("
\end_inset
Continuous random numbers can take on an uncountable number of values.
Therefore, the value returned by a continuous distribution is denoted
\begin_inset Formula $x$
\end_inset
.
Because there is an uncountable number of possibilities for the random
number
\begin_inset Foot
status open
\begin_layout Standard
A computer actually always generates a random number from a discrete distributio
n because there are only a finite set of numbers that can be represented
by a computer.
However, for continuous random number generators, the resulting random
numbers usually approximate the continuous distribution well enough to
ignore the subtlety.
\end_layout
\end_inset
, a continuous distribution is modeled by a probability density function,
\begin_inset Formula $f\left(x;\cdot\right).$
\end_inset
To obtain the probability that the random number generated by
\begin_inset Formula $X\left(\cdot\right)$
\end_inset
is in a certain interval, we integrate this density function:
\begin_inset Formula \[
\int_{-\infty}^{b}f\left(x\right)dx=\textrm{Probability}\left\{ X\left(\cdot\right)\leq b\right\} .\]
\end_inset
\end_layout
\begin_layout Standard
To obtain a probability, we have to integrate
\begin_inset Formula $f\left(x\right)$
\end_inset
which is why it is called a density function.
Most continuous distributions are defined by their probability density
functions (pdf).
Some have basic origins, a few are derived from other distributions, and
some are used mainly for modelling unknown distributions.
\end_layout
\begin_layout Standard
Some of the parameters of the distributions are labeled as location (
\emph on
loc
\emph default
) and
\emph on
scale
\emph default
parameters.
These parameters are not shown in the equation for the pdf.
because they affect the distribution in a known way.
This is due to the fact that if
\begin_inset Formula $X$
\end_inset
is a number drawn from a distribution with pdf
\begin_inset Formula $f_{X}\left(x\right),$
\end_inset
then
\begin_inset Formula $Y=Sx+L$
\end_inset
is a number drawn from a distribution with pdf
\begin_inset Formula \[
f_{Y}\left(y\right)=\frac{1}{S}f_{X}\left(\frac{y-L}{S}\right).\]
\end_inset
Thus, from the standard from provided, the pdf of the actual random numbers
generated by fixing the location and scale parameters can be quickly found.
\end_layout
\begin_layout Standard
In this section, the indicator function
\begin_inset Formula $I_{A}\left(x\right)$
\end_inset
will be used where
\begin_inset Formula $A$
\end_inset
is a set defined over all the real numbers.
For clarity,
\begin_inset Formula \[
I_{A}\left(x\right)=\left\{ \begin{array}{cc}
1 & x\in A,\\
0 & x\not\in A.\end{array}\right.\]
\end_inset
Also, the following functions are used in the definitions:
\begin_inset Formula \begin{eqnarray*}
\Gamma\left(x\right) & = & \int_{0}^{\infty}t^{x-1}e^{-t}dt=\left(x-1\right)\Gamma\left(x-1\right),\\
B\left(a,b\right) & = & \frac{\Gamma\left(a\right)\Gamma\left(b\right)}{\Gamma\left(a+b\right)}.\end{eqnarray*}
\end_inset
\end_layout
\begin_layout Description
beta (
\begin_inset Formula $a$
\end_inset
,
\begin_inset Formula $b$
\end_inset
, size=None)
\end_layout
\begin_layout Standard
\begin_inset Formula \[
f\left(x;a,b\right)=\frac{1}{B\left(a,b\right)}x^{a-1}\left(1-x\right)^{b-1}I_{\left(0,1\right)}\left(x\right).\]
\end_inset
\end_layout
\begin_layout Description
chisquare (
\begin_inset Formula $\nu$
\end_inset
, size=None)
\end_layout
\begin_layout Description
\InsetSpace ~
If
\begin_inset Formula $Z_{1},\ldots,Z_{\nu}$
\end_inset
are random numbers from standard normal distributions, then
\begin_inset Formula $W=\sum_{k=1}^{\nu}Z_{k}^{2}$
\end_inset
is a random number from the chi-square
\begin_inset Formula $\left(\chi^{2}\right)$
\end_inset
distribution with
\begin_inset Formula $\nu$
\end_inset
degrees of freedom.
\end_layout
\begin_layout Standard
\begin_inset Formula \[
f\left(x;\nu\right)=\frac{1}{2\Gamma\left(\frac{\nu}{2}\right)}\left(\frac{x}{2}\right)^{\nu/2-1}e^{-x/2}I_{\left[0,\infty\right)}\left(x\right).\]
\end_inset
\end_layout
\begin_layout Description
dirichlet (
\begin_inset Formula $\boldsymbol{\alpha},$
\end_inset
size=None)
\end_layout
\begin_layout Description
\InsetSpace ~
A vector of random numbers which are drawn from a multivariate Dirichlet
distribution.
The length of the parameter vector,
\begin_inset Formula $\boldsymbol{\alpha},$
\end_inset
is the length,
\begin_inset Formula $N$
\end_inset
, of the random vector.
The joint pdf is:
\end_layout
\begin_layout Description
\begin_inset Formula \[
f\left(\mathbf{x},\boldsymbol{\alpha}\right)=\frac{\prod_{i=1}^{N}\Gamma\left(\alpha_{i}\right)}{\Gamma\left(\sum_{i=1}^{N}\alpha_{i}\right)}\prod_{i=1}^{N}x_{i}^{\alpha_{i}-1}.\]
\end_inset
\series medium
\end_layout
\begin_layout Description
exponential (scale=1.0, size=None)
\end_layout
\begin_layout Standard
\begin_inset Formula \[
f\left(x\right)=e^{-x}I_{\left[0,\infty\right)}\left(x\right).\]
\end_inset
\end_layout
\begin_layout Description
f (
\begin_inset Formula $\nu_{1}$
\end_inset
,
\begin_inset Formula $\nu_{2}$
\end_inset
, size=None)
\end_layout
\begin_layout Description
\InsetSpace ~
The distribution of
\begin_inset Formula $\frac{X_{1}/\nu_{1}}{X_{2}/\nu_{2}}$
\end_inset
where
\begin_inset Formula $X_{i}$
\end_inset
is chi-squared with
\begin_inset Formula $\nu_{i}$
\end_inset
degrees of freedom.
\end_layout
\begin_layout Standard
\begin_inset Formula \[
f\left(x;\nu_{1},\nu_{2}\right)=\frac{\nu_{2}^{\nu_{2}/2}\nu_{1}^{\nu_{1}/2}x^{\nu_{1}/2-1}}{\left(\nu_{2}+\nu_{1}x\right)^{\left(\nu_{1}+\nu_{2}\right)/2}B\left(\frac{\nu_{1}}{2},\frac{\nu_{2}}{2}\right)}I_{\left[0,\infty\right)}\left(x\right).\]
\end_inset
\end_layout
\begin_layout Description
gamma (
\begin_inset Formula $a$
\end_inset
, scale=1.0, size=None)
\end_layout
\begin_layout Standard
\begin_inset Formula \[
f\left(x;a\right)=\frac{1}{\Gamma\left(a\right)}x^{a-1}e^{-x}I_{\left[0,\infty\right)}\left(x\right).\]
\end_inset
\end_layout
\begin_layout Description
gumbel (loc=0.0, scale=1.0, size=None)
\end_layout
\begin_layout Description
\InsetSpace ~
A right-skewed extreme value distribution.
\end_layout
\begin_layout Standard
\begin_inset Formula \[
f\left(x\right)=\exp\left[-x-e^{-x}\right].\]
\end_inset
\end_layout
\begin_layout Description
laplace (loc=0.0, scale=1.0, size=None)
\end_layout
\begin_layout Standard
\begin_inset Formula \[
f\left(x\right)=\frac{1}{2}e^{-\left|x\right|}.\]
\end_inset
\end_layout
\begin_layout Description
lognormal (
\begin_inset Formula $\mu$
\end_inset
=0.0,
\begin_inset Formula $\sigma$
\end_inset
=1.0, size=None)
\end_layout
\begin_layout Standard
\begin_inset Formula \[
f\left(x;\mu,\sigma\right)=\frac{1}{\sigma x\sqrt{2\pi}}\exp\left[-\frac{1}{2}\left(\frac{\log x-\mu}{\sigma}\right)^{2}\right]I_{\left[0,\infty\right)}\left(x\right),\]
\end_inset
The parameters,
\begin_inset Formula $\mu$
\end_inset
and
\begin_inset Formula $\sigma$
\end_inset
are not the mean and variance of this distribution, but the parameters
of the underlying normal distribution.
Random numbers from this distribution are generated as
\begin_inset Formula $e^{\sigma Z+\mu}$
\end_inset
where
\begin_inset Formula $Z$
\end_inset
is a standard normal random number.
\end_layout
\begin_layout Description
logistic (loc=0.0, scale=1.0, size=None)
\begin_inset Formula \[
f\left(x\right)=\frac{e^{-x}}{\left[1+e^{-x}\right]^{2}}I_{\left[0,\infty\right)}\left(x\right)\]
\end_inset
\end_layout
\begin_layout Description
multivariate_normal (
\begin_inset Formula $\mathbf{\boldsymbol{\mu}}$
\end_inset
,
\begin_inset Formula $\mathbf{C}$
\end_inset
, size=None)
\end_layout
\begin_layout Description
\InsetSpace ~
Returns a vector of random numbers which are jointly drawn from a multivariate
normal distribution.
The last-dimension of the output array contains the sample vector, which
is of length
\begin_inset Formula $N=\textrm{len}\left(mean\right).$
\end_inset
The covariance matrix must be
\begin_inset Formula $N\times N$
\end_inset
.
If
\begin_inset Formula $\boldsymbol{\mu}\equiv mean$
\end_inset
and
\begin_inset Formula $\mathbf{C}=cov$
\end_inset
, then the joint-pdf representing the returned random vector(s) is
\begin_inset Formula \[
f\left(\mathbf{x}\right)=\frac{1}{\sqrt{\left(2\pi\right)^{N}\left|\mathbf{C}\right|}}\exp\left[-\frac{1}{2}\left(\mathbf{x}-\boldsymbol{\mu}\right)^{T}\mathbf{C}^{-1}\left(\mathbf{x}-\boldsymbol{\mu}\right)\right].\]
\end_inset
\end_layout
\begin_layout Description
noncentral_chisquare (
\begin_inset Formula $\nu$
\end_inset
,
\begin_inset Formula $\lambda$
\end_inset
, size=None)
\end_layout
\begin_layout Description
\InsetSpace ~
This is the distribution of
\begin_inset Formula $\sum_{i=1}^{\nu}\left(Z_{i}+\delta_{i}\right)^{2}$
\end_inset
where
\begin_inset Formula $Z_{i}$
\end_inset
are independent standard normal random numbers and
\begin_inset Formula $\delta_{i}$
\end_inset
are constants.
It is a a generalized Rayleigh-Rice distribution:
\end_layout
\begin_deeper
\begin_layout Standard
\begin_inset Formula \[
f\left(x;\nu,\lambda\right)=e^{-\left(\lambda+x\right)/2}\frac{1}{2}\left(\frac{x}{\lambda}\right)^{\left(\nu-2\right)/4}I_{\left(\nu-2\right)/2}\left(\sqrt{\lambda x}\right)I_{\left(0,\infty\right)}\left(x\right),\]
\end_inset
where
\begin_inset Formula $I_{\nu}\left(z\right)$
\end_inset
(a real-number in the subscript, not an interval) is the modified Bessel
Function of the first kind.
\end_layout
\end_deeper
\begin_layout Description
noncentral_f (
\begin_inset Formula $\nu_{1}$
\end_inset
,
\begin_inset Formula $\nu_{2}$
\end_inset
,
\begin_inset Formula $\lambda$
\end_inset
, size=None)
\end_layout
\begin_layout Description
\InsetSpace ~
The pdf of this distribution is
\begin_inset Formula \begin{eqnarray*}
f\left(x;\nu_{1},\nu_{2},\lambda\right) & = & \exp\left[\frac{\lambda}{2}+\frac{\lambda v_{1}x}{2\left(\nu_{1}x+\nu_{2}\right)}\right]\nu_{1}^{\nu_{1}/2}\nu_{2}^{\nu_{2}/2}x^{\nu_{1}/2-1}\\
& & \times\left(\nu_{2}+\nu_{1}x\right)^{-\left(\nu_{1}+\nu_{2}\right)/2}\\
& & \times\frac{\Gamma\left(\frac{\nu_{1}}{2}\right)\Gamma\left(1+\frac{\nu_{2}}{2}\right)L_{n_{2}/2}^{n_{1}/2-1}\left(-\frac{\lambda\nu_{1}x}{2\left(\nu_{1}x+\nu_{2}\right)}\right)}{B\left(\frac{\nu_{1}}{2},\frac{\nu_{2}}{2}\right)\Gamma\left(\frac{\nu_{1}+\nu_{2}}{2}\right)}.\end{eqnarray*}
\end_inset
\end_layout
\begin_layout Description
normal (loc=0.0, scale=1.0, size=None)
\end_layout
\begin_layout Description
\InsetSpace ~
The normal, or Gaussian, distribution is the limiting distribution of independe
nt samples from any sufficiently well-behaved distributions (this is the
content of the celebrated central limit theorem).
The normal distribution is also the distribution of maximum entropy when
the mean and variance alone are fixed.
These two facts account for its name as well as the wide variety of situations
that can be usefully modelled using the normal distribution.
Because it is so widely used, the full pdf with the location
\begin_inset Formula $\left(\mu\right)$
\end_inset
and scale
\begin_inset Formula $\left(\sigma\right)$
\end_inset
parameters is provided:
\end_layout
\begin_layout Standard
\begin_inset Formula \[
f\left(x\right)=\frac{1}{\sigma\sqrt{2\pi}}\exp\left[-\frac{\left(x-\mu\right)^{2}}{2\sigma^{2}}\right].\]
\end_inset
\end_layout
\begin_layout Description
pareto (
\begin_inset Formula $a$
\end_inset
, size=None)
\end_layout
\begin_layout Standard
\begin_inset Formula \[
f\left(x;a\right)=\frac{a}{x^{a+1}}I_{\left[1,\infty\right)}\left(x\right).\]
\end_inset
\end_layout
\begin_layout Description
power (
\begin_inset Formula $a$
\end_inset
, size=None)
\end_layout
\begin_layout Description
\InsetSpace ~
A special case of the beta distribution with
\begin_inset Formula $b=1.$
\end_inset
\end_layout
\begin_layout Standard
\begin_inset Formula \[
f\left(x;a\right)=ax^{a-1}I_{\left[0,1\right]}\left(x\right).\]
\end_inset
\end_layout
\begin_layout Description
rand (
\begin_inset Formula $d_{1}$
\end_inset
,
\begin_inset Formula $d_{2}$
\end_inset
,
\begin_inset Formula $\ldots$
\end_inset
,
\begin_inset Formula $d_{n}$
\end_inset
)
\end_layout
\begin_layout Description
\InsetSpace ~
A convenient interface to obtain an array of shape
\begin_inset Formula $\left(d_{1},d_{2},\ldots,d_{n}\right)$
\end_inset
of uniform random numbers in the interval
\begin_inset Formula $\left[0,1\right).$
\end_inset
Notice the different convention for passing in the shape (as separate arguments
instead of a tuple).
The standard convention is used in the function numpy.random.random(shape)
for which this function is merely a convenient short-hand.
If you have a tuple named shape, then rand(*shape) will work correctly.
\end_layout
\begin_layout Description
randint (low, high=None, size=None)
\end_layout
\begin_layout Description
\InsetSpace ~
Equally probably random integers in the range
\begin_inset Formula $low\leq x.py.
These test files should then define sub-classes of NumpyTestCase (or unittest.Te
stCase) named
\begin_inset Quotes eld
\end_inset
test*
\begin_inset Quotes erd
\end_inset
.
These classes should then define functions named
\begin_inset Quotes eld
\end_inset
test*
\begin_inset Quotes erd
\end_inset
or
\begin_inset Quotes eld
\end_inset
bench*
\begin_inset Quotes erd
\end_inset
or
\begin_inset Quotes eld
\end_inset
check*
\begin_inset Quotes erd
\end_inset
that contain the actual unit-tests.
The first keyword argument should specify the level above which this test
should be run.
\end_layout
\begin_layout Description
\InsetSpace ~
To run the tests excecute NumpyTest().test(level=1, verbosity=1)
which will run all tests above the given level using the given verbosity.
Here can be either a string or a previously imported module.
You can get the level and verbosity arguments from sys.argv using NumpyTest().run() with -v or --verbosity and -l or --level as command-line arguments.
\end_layout
\begin_layout Description
set_local_path (reldir='', level=1)
\end_layout
\begin_layout Description
\InsetSpace ~
prepend local directory (+ reldir) to sys.path.
The caller is responsible for removing this path using restore_path().
\end_layout
\begin_layout Description
set_package_path (level=1)
\end_layout
\begin_layout Description
\InsetSpace ~
prepend package directory to sys.path.
This should be called from a test_file.py that satisfies the tree structure:
//test_file.py.
The, the first existing path name from the list /build/lib.-
, /..
is pre-pended to sys.path.
The caller is responsible for removing this path using restore_path().
\end_layout
\begin_layout Description
restore_path ()
\end_layout
\begin_layout Description
\InsetSpace ~
Remove the first entry from sys.path.
\end_layout
\begin_layout Description
assert_equal (actual, desired, err_msg='', verbose=1)
\end_layout
\begin_layout Description
\InsetSpace ~
Raise an assertion error if the two items are not equal.
Automatically calls assert_array_equal if actual or desired is an ndarray.
\end_layout
\begin_layout Description
assert_almost_equal (actual, desired, decimal=7, err_msg='', verbose=1)
\end_layout
\begin_layout Description
\InsetSpace ~
Raise an assertion error if the two items are not equal within decimal
places.
Automatically calls assert_array_almost_equal if actual or desired is an
ndarray.
\end_layout
\begin_layout Description
assert_approx_equal (actual, desired, significant=7, err_msg='', verbose=1)
\end_layout
\begin_layout Description
\InsetSpace ~
Raise an assertion error if the two items are not equal to within the given
significant digits.
Does not work on arrays.
\end_layout
\begin_layout Description
assert_array_equal (x, y, err_msg='')
\end_layout
\begin_layout Description
\InsetSpace ~
Raise an error if the two arrays x and y are not equal at every element.
\end_layout
\begin_layout Description
assert_array_less (x, y, err_msg='')
\end_layout
\begin_layout Description
\InsetSpace ~
Raise an error if the two arrays x and y have different shapes or if x
is not less than y at every element.
\end_layout
\begin_layout Description
assert_array_almost_equal (x, y, decimal=6, err_msg='')
\end_layout
\begin_layout Description
\InsetSpace ~
Raise an error if x and y are not equal to decimal places at every element.
\end_layout
\begin_layout Description
jiffies ()
\end_layout
\begin_layout Description
\InsetSpace ~
Return a number of 1/100ths of a second that this process has been scheduled
in user mode.
Implemented using time.time() unless on Linux where the special /proc directory
filesystem is used.
\end_layout
\begin_layout Description
memusage ()
\end_layout
\begin_layout Description
\InsetSpace ~
Return the virtual memory size in bytes of the running python.
If the operation is not supported on the platform, then return None.
This works only on linux for now.
\end_layout
\begin_layout Description
rand (*args)
\end_layout
\begin_layout Description
\InsetSpace ~
Return an array of random numbers with the given shape using only the standard
library random number generator.
\end_layout
\begin_layout Description
runstring (astr, dict)
\end_layout
\begin_layout Description
\InsetSpace ~
Run the given string in the dictionary provided.
Functional form for (exec astr in dict) that is useful for the failUnlessRaises
method of unittest.TestCase class.
\end_layout
\begin_layout Section
NumPy Distutils
\end_layout
\begin_layout Standard
\begin_inset LatexCommand index
name "distutils"
\end_inset
NumPy provides enhanced distutils functionality to make it easier to build
and install sub-packages, auto-generate code, and extension modules that
use Fortran-compiled libraries.
To use features of numpy distutils use the setup command from numpy.distutils.cor
e.
A useful Configuration class is also provided in numpy.distutils.misc_util
that can make it easier to construct keyword arguments to pass to the setup
function (by passing the dictionary obtained from the todict() method of
the class).
More information is available in the NumPy Distutils Users Guide in /numpy/doc/DISTUTILS.txt.
\end_layout
\begin_layout Subsection
misc_util
\end_layout
\begin_layout Description
Configuration (package_name=None, parent_name=None, top_path=None, package_path=
None, **attrs)
\end_layout
\begin_layout Description
\InsetSpace ~
\begin_inset LatexCommand index
name "Configuration"
\end_inset
Construct a configuration instance for the given package name.
If parent_name is not None, then construct the package as a sub-package
of the parent_name package.
If top_path and package_path are None then they are assumed equal to the
path of the file this instance was created in.
The setup.py files in the numpy distribution are good examples of how to
use the Configuration instance.
\end_layout
\begin_deeper
\begin_layout Description
self.todict ()
\end_layout
\begin_layout Description
\InsetSpace ~
Return a dictionary compatible with the keyword arguments of distutils
setup function.
Thus, this method may be used as setup(**config.todict()).
\end_layout
\begin_layout Description
self.get_distribution ()
\end_layout
\begin_layout Description
\InsetSpace ~
Return the distutils distribution object for self.
\end_layout
\begin_layout Description
self.get_subpackage (subpackage_name, subpackage_path=None)
\end_layout
\begin_layout Description
\InsetSpace ~
Return a Configuration instance for the sub-package given.
If subpackage_path is None then the path is assumed to be the local path
plus the subpackage_name.
If a setup.py file is not found in the subpackage_path, then a default configura
tion is used.
\end_layout
\begin_layout Description
self.add_subpackage (subpackage_name, subpackage_path=None)
\end_layout
\begin_layout Description
\InsetSpace ~
Add a sub-package to the current Configuration instance.
This is useful in a setup.py script for adding sub-packages to a package.
The sub-package is contained in subpackage_path / subpackage_name and this
directory may contain a setup.py script or else a default setup (suitable
for Python-code-only subpackages) is assumed.
If the subpackage_path is None, then it is assumed to be located in the
local path / subpackage_name.
\end_layout
\begin_layout Description
self.add_data_files (*files)
\end_layout
\begin_layout Description
\InsetSpace ~
Add files to the list of data_files to be included with the package.
The form of each element of the files sequence is very flexible allowing
many combinations of where to get the files from the package and where
they should ultimately be installed on the system.
The most basic usage is for an element of the files argument sequence to
be a simple filename.
This will cause that file from the local path to be installed to the installati
on path of the self.name package (package path).
The file argument can also be a relative path in which case the entire
relative path will be installed into the package directory.
Finally, the file can be an absolute path name in which case the file will
be found at the absolute path name but installed to the package path.
\end_layout
\begin_layout Description
\InsetSpace ~
This basic behavior can be augmented by passing a 2-tuple in as the file
argument.
The first element of the tuple should specify the relative path (under
the package install directory) where the remaining sequence of files should
be installed to (it has nothing to do with the file-names in the source
distribution).
The second element of the tuple is the sequence of files that should be
installed.
The files in this sequence can be filenames, relative paths, or absolute
paths.
For absolute paths the file will be installed in the top-level package
installation directory (regardless of the first argument).
Filenames and relative path names will be installed in the package install
directory under the path name given as the first element of the tuple.
An example may clarify:
\end_layout
\begin_deeper
\begin_layout LyX-Code
self.add_data_files('foo.dat',
\newline
('fun', ['gun.dat', 'nun/pun.dat', '/tmp/sun.dat']),
\newline
'bar/cat.dat',
\newline
'/full/path/to/can.dat')
\end_layout
\begin_layout Standard
will install these data files to:
\end_layout
\begin_layout LyX-Code
/
\newline
foo.dat
\newline
fun/
\newline
gun.dat
\newline
nun/
\newline
pun.dat
\newline
sun.dat
\newline
bar/
\newline
car.dat
\newline
can.dat
\end_layout
\begin_layout Standard
where is the package (or sub-package) directory
such as '/usr/lib/python2.4/site-packages/mypackage' ('C:
\backslash
\backslash
Python2.4
\backslash
\backslash
Lib
\backslash
\backslash
site-packages
\backslash
\backslash
mypackage') or '/usr/lib/python2.4/site-packages/mypackage/mysubpackage'
('C:
\backslash
\backslash
Python2.4
\backslash
\backslash
Lib
\backslash
\backslash
site-packages
\backslash
\backslash
mypackage
\backslash
\backslash
mysubpackage').
\end_layout
\end_deeper
\begin_layout Standard
\InsetSpace ~
An additional feature is that the path to a data-file can actually be a
function that takes no arguments and returns the actual path(s) to the
data-files.
This is useful when the data files are generated while building the package.
\end_layout
\begin_layout Description
self.add_data_dir (data_path)
\end_layout
\begin_layout Description
\InsetSpace ~
Recursively add files under data_path to the list of data_files to be installed
(and distributed).
The data_path can be either a relative path-name, or an absolute path-name,
or a 2-tuple where the first argument shows where in the install directory
the data directory should be installed to.
For example suppose the source directory contains fun/foo.dat and fun/bar/car.dat
\end_layout
\begin_layout LyX-Code
self.add_data_dir('fun')
\newline
self.add_data_dir(('sun', 'fun'))
\newline
self.add_data_dir(('gun',
'/full/path/to/fun'))
\end_layout
\begin_layout Standard
\InsetSpace ~
Will install data-files to the locations
\end_layout
\begin_layout LyX-Code
/
\newline
fun/
\newline
foo.dat
\newline
bar/
\newline
car.dat
\newline
sun/
\newline
foo.dat
\newline
bar/
\newline
car.dat
\newline
gun/
\newline
foo.dat
\newline
car.dat
\end_layout
\begin_layout Description
self.add_include_dirs (*paths)
\end_layout
\begin_layout Description
\InsetSpace ~
Add the given sequence of paths to the beginning of the include_dirs list.
This list will be visible to all extension modules of the current package.
\end_layout
\begin_layout Description
self.add_headers (*files)
\end_layout
\begin_layout Description
\InsetSpace ~
Add the given sequence of files to the beginning of the headers list.
By default, headers will be installed under // directory.
If an item of files is a tuple, then its first argument specifies the actual
installation location relative to the path.
\end_layout
\begin_layout Description
self.add_extension (name, sources, **kw)
\end_layout
\begin_layout Description
\InsetSpace ~
Create and add an Extension instance to the ext_modules list.
The first argument defines the name of the extension module that will be
installed under the self.name package.
The second argument is a list of sources.
This method also takes the following optional keyword arguments that are
passed on to the Extension constructor: include_dirs, define_macros, undef_macr
os, library_dirs, libraries, runtime_library_dirs, extra_objects, swig_opts,
depends, language, f2py_options, module_dirs, and extra_info.
\end_layout
\begin_layout Description
\InsetSpace ~
The self.paths(...) method is applied to all lists that may contain paths.
The extra_info is a dictionary or a list of dictionaries whose content
will be appended to the keyword arguments.
The depends list contains paths to files or directories that the sources
of the extension module depend on.
If any path in the depends list is newer than the extension module, then
the module will be rebuilt.
\end_layout
\begin_layout Description
\InsetSpace ~
The list of sources may contain functions (called source generators) which
must take an extension instance and a build directory as inputs and return
a source file or list of source files or None.
If None is returned then no sources are generated.
If the Extension instance has no sources after processing all source generators
, then no extension module is built.
\end_layout
\begin_layout Description
self.add_library (name, sources, **build_info)
\end_layout
\begin_layout Description
\InsetSpace ~
Add a library to the list of libraries.
Allowed keyword arguments are depends, macros, include_dirs, extra_compiler_arg
s, and f2py_options.
The name is the name of the library to be built and sources is a list of
sources (or source generating functions) to add to the library.
\end_layout
\begin_layout Description
self.add_scripts (*files)
\end_layout
\begin_layout Description
\InsetSpace ~
Add the sequence of files to the beginning of the scripts list.
Scripts will be installed under the /bin/ directory.
\end_layout
\begin_layout Description
self.paths (*paths)
\end_layout
\begin_layout Description
\InsetSpace ~
Applies glob.glob(...) to each path in the sequence (if needed) and pre-pends
the local_path if needed.
Because this is called on all source lists, this allows wildcard characters
to be specified in lists of sources for extension modules and libraries
and scripts and allows path-names be relative to the source directory.
\end_layout
\begin_layout Description
self.get_config_cmd ()
\end_layout
\begin_layout Description
\InsetSpace ~
Returns the numpy.distutils config command instance.
\end_layout
\begin_layout Description
self.get_build_temp_dir ()
\end_layout
\begin_layout Description
\InsetSpace ~
Return a path to a temporary directory where temporary files should be
placed.
\end_layout
\begin_layout Description
self.have_f77c ()
\end_layout
\begin_layout Description
\InsetSpace ~
True if a Fortran 77 compiler is available (because a simple Fortran 77
code was able to be compiled successfully).
\end_layout
\begin_layout Description
self.have_f90c ()
\end_layout
\begin_layout Description
\InsetSpace ~
True if a Fortran 90 compiler is available (because a simple Fortran 90
code was able to be compiled successfully)
\end_layout
\begin_layout Description
self.get_version ()
\end_layout
\begin_layout Description
\InsetSpace ~
Return a version string of the current package or None if the version informati
on could not be detected.
This method scans files named __version__.py, _version.py, version.py
, and __svn_version__.py for string variables version, __version__, and _version, until a version number is found.
\end_layout
\begin_layout Description
self.make_svn_version_py ()
\end_layout
\begin_layout Description
\InsetSpace ~
Appends a data function to the data_files list that will generate __svn_version
__.py file to the current package directory.
This file will be removed from the source directory when Python exits (so
that it can be re-generated next time the package is built).
This is intended for working with source directories that are in an SVN
repository.
\end_layout
\begin_layout Description
self.make_config_py ()
\end_layout
\begin_layout Description
\InsetSpace ~
Generate a package __config__.py file containing system information used
during the building of the package.
This file is installed to the package installation directory.
\end_layout
\begin_layout Description
self.get_info (*names)
\end_layout
\begin_layout Description
\InsetSpace ~
Return information (from system_info.get_info) for all of the names in the
argument list in a single dictionary.
\end_layout
\end_deeper
\begin_layout Description
get_numpy_include_dirs ()
\end_layout
\begin_layout Description
\InsetSpace ~
Return the include directory where the numpy/arrayobject.h and numpy/ufuncobject.
h files are found.
This should be added to the include_dirs of any extension module built
using NumPy.
If numpy.distutils is used to build the extension, then this directory is
added automatically.
\end_layout
\begin_layout Description
get_numarray_include_dirs ()
\end_layout
\begin_layout Description
\InsetSpace ~
Return the include directory where the numpy/libnumarray.h file is found.
This should be added to the include_dirs of any extension module that relies
on the Numarray-compatible C-API.
\end_layout
\begin_layout Description
dict_append (d, **kwds)
\end_layout
\begin_layout Description
\InsetSpace ~
Add the keyword arguments given as entries in the dictionary provided as
the first argument.
If the entry is already present, then assume it is a list and extend the
list with the keyword value.
\end_layout
\begin_layout Description
appendpath (prefix, path)
\end_layout
\begin_layout Description
\InsetSpace ~
Platform-independent intelligence for appending path to prefix.
It replaces '/' in the prefix and the path with the correct path-separator
on the platform ad returns a full path name that will be valid for the
platform.
\end_layout
\begin_layout Description
allpath (name)
\end_layout
\begin_layout Description
\InsetSpace ~
Convert a '/' separated pathname to one using the platform's path separator.
\end_layout
\begin_layout Description
dot_join (*args)
\end_layout
\begin_layout Description
\InsetSpace ~
Converts a sequence of string arguments to a string joined by '.' (removing
any empty strings).
\end_layout
\begin_layout Description
generate_config_py (extension, build_dir)
\end_layout
\begin_layout Description
\InsetSpace ~
A suitable function that can be used in a source list.
This constructs a python file that contains system_info information used
during building the package.
Generally easier to use a Configuration instance and the config.make_config_py()
method.
\end_layout
\begin_layout Description
get_cmd (cmdname, _cache={})
\end_layout
\begin_layout Description
\InsetSpace ~
Returns an instance of the distutils command object named cmdname if the
setup distribution instance has been initialized.
Caches the result in _cache[cmdname] and gets it from there if present.
\end_layout
\begin_layout Description
terminal_has_colors ()
\end_layout
\begin_layout Description
\InsetSpace ~
Tries to determine if the stdout terminal can be written to using ANSI
colors.
Returns 1 if it can be determined that ANSI colors are acceptable or 0
if not.
\end_layout
\begin_layout Description
red_text (s)
\end_layout
\begin_layout Description
green_text (s)
\end_layout
\begin_layout Description
yellow_text (s)
\end_layout
\begin_layout Description
blue_text (s)
\end_layout
\begin_layout Description
cyan_text (s)
\end_layout
\begin_layout Description
\InsetSpace ~
If terminal_has_colors() is true, then these commands return a string with
the necessary codes prepended to display the given string argument in the
specified color on an ANSI terminal.
If terminal_has_colors() is false, then these functions simply return the
input argument.
\end_layout
\begin_layout Description
cyg2win32 (path)
\end_layout
\begin_layout Description
\InsetSpace ~
Convert a cygwin path beginning with /cygdrive to a standard win32 path
name.
\end_layout
\begin_layout Description
all_strings (lst)
\end_layout
\begin_layout Description
\InsetSpace ~
Return True if all items in the input list are string objects otherwise
return False.
\end_layout
\begin_layout Description
has_f_sources (sources)
\end_layout
\begin_layout Description
\InsetSpace ~
Return True if any of the source files listed in the input argument are
Fortran files because its name matches against the compiled regular expression
\series bold
fortran_ext_match
\series default
.
\end_layout
\begin_layout Description
has_cxx_sources (sources)
\end_layout
\begin_layout Description
\InsetSpace ~
Return True if any of the source files listed in the input argument are
C++ files because its name matches against the compiled regular expression
\series bold
cxx_ext_match
\series default
.
\end_layout
\begin_layout Description
filter_sources (sources)
\end_layout
\begin_layout Description
\InsetSpace ~
From the provided list of sources, return four lists of filenames containing
C, C++, Fortran, and Fortran 90 module sources respectively.
The compiled regular expressions used in this search (which are also available
in the misc_util module) are cxx_ext_match, fortran_ext_match, f90_ext_match,
and f90_module_name_match.
\end_layout
\begin_layout Description
get_dependencies (sources)
\end_layout
\begin_layout Description
\InsetSpace ~
Scan the files in the sources list for include statements.
\end_layout
\begin_layout Description
is_local_src_dir (directory)
\end_layout
\begin_layout Description
\InsetSpace ~
Return True if the provided directory is the local current working directory.
\end_layout
\begin_layout Description
get_ext_source_files (ext)
\end_layout
\begin_layout Description
\InsetSpace ~
Get sources and any include files in the same directory from an Extension
instance.
\end_layout
\begin_layout Description
get_script_files (scripts)
\end_layout
\begin_layout Description
\InsetSpace ~
Returns the list scripts with all non-string arguments removed.
\end_layout
\begin_layout Subsection
Other modules
\end_layout
\begin_layout Description
system_info.get_info (name)
\end_layout
\begin_layout Description
\InsetSpace ~
For the given string representing a particular resource, return a dictionary
that is compatible with the distutils.setup keyword arguments.
If this is an empty dictionary, then the requested resource is not available.
Some of the names that can be checked are 'lapack_opt', 'blas_opt', 'fft_opt',
'fftw', 'fftw3', 'fftw2', 'djbfft', 'numpy', 'numarray', 'boost_python',
'agg2', 'wx', 'gdk', 'xft', 'freetype2'.
\end_layout
\begin_layout Description
system_info.get_standard_file (filename)
\end_layout
\begin_layout Description
\InsetSpace ~
Return a list of length 0 to 3 containing the full-path filenames for the
filename provided.
The filename is searched for in three places in the following order 1)
the system-wide location which is the directory that the system_info file
is located in; 2) the directory specified by the environment variable HOME;
and 3) the current local directory.
\end_layout
\begin_layout Description
cpuinfo.cpu an instance of a cpuinfo class that defines methods for checking
various aspects of the cpu.
The info attribute is a list of length (# of CPUs).
Each entry is a dictionary providing technical information about that CPU.
\end_layout
\begin_layout Description
log.set_verbosity (level)
\end_layout
\begin_layout Description
\InsetSpace ~
Set the distutils logging threshold and return the previously stored value.
The level is an integer that corresponds to distutils.log thresholds: -1
<--> ERROR, 0 <--> WARN, 1 <--> INFO, and 2 <--> DEBUG.
\end_layout
\begin_layout Description
exec_command
\end_layout
\begin_deeper
\begin_layout Description
exec_command (command, execute_in='', use_shell=None, use_tee=None, _with_python
=1, **env)
\end_layout
\begin_layout Description
\InsetSpace ~
Return (status, output) of the executed command.
The command input is a string of executable and arguments.
The output contains both stderr and stdout messages.
If execute_in is given, then change to the provided directory prior to
executing the command and afterwords restore to the current directory.
On NT, and DOS systems the returned status is correct for external commands.
However, wild cards will not work for non-posix systems.
\end_layout
\begin_layout Description
splitcmdline (line)
\end_layout
\begin_layout Description
\InsetSpace ~
Inverse of ' '.join(sys.argv)
\end_layout
\begin_layout Description
find_executable (exe, path=None)
\end_layout
\begin_layout Description
\InsetSpace ~
Return full path of an executable using information from the PATH environment
variable.
Equivalent to the POSIX 'which' command.
\end_layout
\begin_layout Description
get_pythonexe ()
\end_layout
\begin_layout Description
\InsetSpace ~
Return the full path to the python executable with some fixes for nt and
dos to replace pythonw with python if it is encountered.
A basic wrapper around sys.executable.
\end_layout
\end_deeper
\begin_layout Section
Conversion of .src files
\end_layout
\begin_layout Standard
\begin_inset LatexCommand index
name "code generation"
\end_inset
NumPy distutils supports automatic conversion of source files named .sr
c.
This facility can be used to maintain very similar code blocks requiring
only simple changes between blocks.
During the build phase of setup, if a template file named .src
is encountered, a new file named is constructed from the template
and placed in the build directory to be used instead.
Two forms of template conversion are supported.
The first form occurs for files named named .ext.src where ext is a
recognized Fortran extension (f, f90, f95, f77, for, ftn, pyf).
The second form is used for all other cases.
\end_layout
\begin_layout Subsection
Fortran files
\end_layout
\begin_layout Standard
This template converter will replicate all
\series bold
function
\series default
and
\series bold
subroutine
\series default
blocks in the file with names that contain '<...>' according to the rules
in '<...>'.
The number of comma-separated words in '<...>' determines the number of times
the block is repeated.
What these words are indicates what that repeat rule, '<...>', should be replaced
with in each block.
All of the repeat rules in a block must contain the same number of comma-separa
ted words indicating the number of times that block should be repeated.
If the word in the repeat rule needs a comma, leftarrow, or rightarrow,
then prepend it with a backslash '
\backslash
'.
If a word in the repeat rule matches '
\backslash
\backslash
' then it will be replaced with the -th word in the same repeat
specification.
There are two forms for the repeat rule: named and short.
\end_layout
\begin_layout Subsubsection
Named repeat rule
\end_layout
\begin_layout Standard
A named repeat rule is useful when the same set of repeats must be used
several times in a block.
It is specified using , where N is the
number of times the block should be repeated.
On each repeat of the block, the entire expression, '<...>' will be replaced
first with item1, and then with item2, and so forth until N repeats are
accomplished.
Once a named repeat specification has been introduced, the same repeat
rule may be used
\series bold
in the current block
\series default
by referring only to the name (i.e.
.
\end_layout
\begin_layout Subsubsection
Short repeat rule
\end_layout
\begin_layout Standard
A short repeat rule looks like .
The rule specifies that the entire expression, '<...>' should be replaced
first with item1, and then with item2, and so forth until N repeats are
accomplished.
\end_layout
\begin_layout Subsubsection
Pre-defined names
\end_layout
\begin_layout Standard
The following predefined named repeat rules are available:
\end_layout
\begin_layout Itemize
\end_layout
\begin_layout Itemize
<_c=s,d,c,z>
\end_layout
\begin_layout Itemize
<_t=real, double precision, complex, double complex>
\end_layout
\begin_layout Itemize
\end_layout
\begin_layout Itemize
\end_layout
\begin_layout Itemize
\end_layout
\begin_layout Itemize
\end_layout
\begin_layout Subsection
Other files
\end_layout
\begin_layout Standard
Non-Fortran files use a separate syntax for defining template blocks that
should be repeated using a variable expansion similar to the named repeat
rules of the Fortran-specific repeats.
The template rules for these files are:
\end_layout
\begin_layout Enumerate
\begin_inset Quotes eld
\end_inset
/**begin repeat
\begin_inset Quotes erd
\end_inset
on a line by itself marks the beginning of a segment that should be repeated.
\end_layout
\begin_layout Enumerate
Named variable expansions are defined using #name=item1, item2, item3, ...,
itemN# and placed on successive lines.
These variables are replaced in each repeat block with corresponding word.
All named variables in the same repeat block must define the same number
of words.
\end_layout
\begin_layout Enumerate
In specifying the repeat rule for a named variable, item*N is short-hand
for item, item, ..., item repeated N times.
In addition, parenthesis in combination with *N can be used for grouping
several items that should be repeated.
Thus, #name=(item1, item2)*4# is equivalent to #name=item1, item2, item1,
item2, item1, item2, item1, item2#
\end_layout
\begin_layout Enumerate
\begin_inset Quotes eld
\end_inset
*/
\begin_inset Quotes erd
\end_inset
on a line by itself marks the end of the the variable expansion naming.
The next line is the first line that will be repeated using the named rules.
\end_layout
\begin_layout Enumerate
Inside the block to be repeated, the variables that should be expanded are
specified as @name@.
\end_layout
\begin_layout Enumerate
\begin_inset Quotes eld
\end_inset
/**end repeat**/
\begin_inset Quotes erd
\end_inset
on a line by itself marks the previous line as the last line of the block
to be repeated.
\end_layout
\begin_layout Standard
\begin_inset Include \input{capi.lyx}
preview false
\end_inset
\end_layout
\begin_layout Standard
\begin_inset LatexCommand printindex
\end_inset
\end_layout
\end_body
\end_document