You are on page 1of 13

NumPy for IDL users Mathesaurus

http://mathesaurus.sourceforge.net/idl-numpy.html

NumPy for IDL users


Help
IDL ? ?help ?plot Python help() help Description

or man,'plot

help(plot)

or ?plot

help(pylab) demo

Browse help interactively Help on using help Help for a function Help for a toolbox/library package Demonstration examples

Searching available documentation


IDL Python help(); modules [Numeric] help(plot) Description

List available packages Locate functions

Using interactively
IDL idlde Python ipython -pylab TAB @"foo.idlbatch" help,/rec journal,'IDLhistory' exit Description

or .run

'foo.pro' execfile('foo.py') hist -n

or run

foo.py

or CTRL-D

CTRL-D CTRL-Z # windows sys.exit()

Start session Auto completion Run code from file Command history Save command history End session

Operators
IDL Python Description

Arithmetic operators
IDL a=1 & b=1 a + b a - b a * b a / b a ^ b Python a=1; b=1 a + b a a * a / Description

or add(a,b) b or subtract(a,b) b or multiply(a,b) b or divide(a,b)

a ** b power(a,b)

Assignment; defining a number Addition Subtraction Multiplication Division Power, $a^b$

1 of 13

2/4/2014 2:52 PM

NumPy for IDL users Mathesaurus

http://mathesaurus.sourceforge.net/idl-numpy.html

pow(a,b) a MOD b a % b remainder(a,b) fmod(a,b) ++a a++ a+=1 a+=b

Remainder

or a+=1 or add(a,b,a)

Increment, return new value Increment, return old value In place operation to save array creation overhead

Relational operators
IDL a eq b a lt b a gt b a le b a ge b a ne b Python a == b a a a a a Description

or equal(a,b) < b or less(a,b) > b or greater(a,b) <= b or less_equal(a,b) >= b or greater_equal(a,b) != b or not_equal(a,b)

Equal Less than Greater than Less than or equal Greater than or equal Not Equal

Logical operators
IDL Python a and b a or b a and b a or b a xor b not a Description

or a and logical_or(a,b) or a or b
logical_and(a,b) logical_xor(a,b) logical_not(a)

or not

Short-circuit logical AND Short-circuit logical OR Element-wise logical AND Element-wise logical OR Logical EXCLUSIVE OR Logical NOT

root and logarithm


IDL sqrt(a) alog(a) alog10(a) Python math.sqrt(a) math.log(a) math.log10(a) math.log(a, 2) exp(a) math.exp(a) Description

Square root Logarithm, base $e$ (natural) Logarithm, base 10 Logarithm, base 2 (binary) Exponential function

Round off
IDL round(a) ceil(a) floor(a) Python around(a) ceil(a) floor(a) fix(a) Description

or math.round(a)

Round Round up Round down Round towards zero

2 of 13

2/4/2014 2:52 PM

NumPy for IDL users Mathesaurus

http://mathesaurus.sourceforge.net/idl-numpy.html

Mathematical constants
IDL !pi exp(1) Python math.pi math.e Description

or math.exp(1)

$\pi=3.141592$ $e=2.718281$

Missing values; IEEE-754 floating point status flags


IDL Python nan inf plus_inf minus_inf plus_zero minus_zero Description

Not a Number Infinity, $\infty$ Infinity, $+\infty$ Infinity, $-\infty$ Plus zero, $+0$ Minus zero, $-0$

Complex numbers
IDL complex(0,1) z = complex(3,4) abs(z) real_part(z) imaginary(z) conj(z) Python z = 1j z = 3+4j Description

or z

= complex(3,4)

abs(3+4j) z.real z.imag z.conj(); z.conjugate()

Imaginary unit A complex number, $3+4i$ Absolute value (modulus) Real part Imaginary part Complex conjugate

Trigonometry
IDL Python atan2(b,a) hypot(x,y) Description

Arctangent, $\arctan(b/a)$ Hypotenus; Euclidean distance

Generate random numbers


IDL randomu(seed, 10) Python random.random((10,)) random.uniform((10,)) 2+5*randomu(seed, 10) random.uniform(2,7,(10,)) Description

Uniform distribution Uniform: Numbers between 2 and 7 Uniform: 6,6 array Normal distribution

randomu(seed,[6,6]) randomn(seed, 10)

random.uniform(0,1,(6,6)) random.standard_normal((10,))

Vectors
IDL Python Description

3 of 13

2/4/2014 2:52 PM

NumPy for IDL users Mathesaurus

http://mathesaurus.sourceforge.net/idl-numpy.html

a = [2, 3, 4, 5]

a=array([2,3,4,5])

transpose([2,3,4,5])

array([2,3,4,5])[:,NewAxis] array([2,3,4,5]).reshape(-1,1) r_[1:10,'c']

Row vector, $1 \times n$-matrix Column vector, $m \times 1$-matrix

Sequences
IDL indgen(10)+1 dindgen(10)+1 dindgen(10) indgen(4)*3+1 Python arange(1,11, dtype=Float) range(1,11) arange(10.) arange(1,11,3) arange(10,0,-1) arange(10,0,-3) linspace(1,10,7) Description

1,2,3, ... ,10 0.0,1.0,2.0, ... ,9.0 1,4,7,10 10,9,8, ... ,1 10,7,4,1 Linearly spaced vector of n=7 points Reverse Set all values to same scalar value

reverse(a)

a[::-1]

or

a.fill(3), a[:] = 3

Concatenation (vectors)
IDL [a,a] Python Description

or rebin(a,2,size(a))

concatenate((a,a)) concatenate((range(1,5),a), axis=1)

Concatenate two vectors

[indgen(3)+1,a]

Repeating
IDL Python concatenate((a,a)) Description

or a.repeat(a) or
a.repeat(3)

1 2 3, 1 2 3 1 1 1, 2 2 2, 3 3 3 1, 2 2, 3 3 3

Miss those elements out


IDL Python a[1:] a[-1] a[-2:] Description

miss the first element last element last two elements

Maximum and minimum


IDL Python maximum(a,b) concatenate((a,b)).max() Description

pairwise max max of all values in two vectors

4 of 13

2/4/2014 2:52 PM

NumPy for IDL users Mathesaurus

http://mathesaurus.sourceforge.net/idl-numpy.html

v,i = a.max(0),a.argmax(0)

Vector multiplication
IDL Python a*a crossp(u,v) dot(u,v) Description

Multiply two vectors Vector cross product, $u \times v$ Vector dot product, $u \cdot v$

Matrices
IDL a = [[2,3],[4,5]] Python a = array([[2,3],[4,5]]) Description

Define a matrix

Concatenation (matrices); rbind and cbind


IDL Python concatenate((a,b), axis=0) vstack((a,b)) concatenate((a,b), axis=1) hstack((a,b)) concatenate((a,b), axis=2) dstack((a,b)) Description

Bind rows Bind columns Bind slices (three-way arrays)

Concatenate matrices into one vector concatenate((r_[1:5],r_[1:5])).reshape(2,-1) Bind rows (from vectors)
concatenate((a,b), axis=None) vstack((r_[1:5],r_[1:5]))

Array creation
IDL dblarr(3,5) intarr(3,5) dblarr(3,5)+1 intarr(3,5)+9 identity(3) diag_matrix([4,5,6]) identity(3) diag((4,5,6)) a = empty((3,3)) Python zeros((3,5),Float) zeros((3,5)) ones((3,5),Float) Description

0 filled array 0 filled array of integers 1 filled array Any number filled array Identity matrix Diagonal Empty array

Reshape and flatten matrices


IDL reform(a,2,3) Python arange(1,7).reshape(2,-1) a.setshape(2,3) arange(1,7).reshape(-1,2).transpose() Description

Reshaping (rows first) Reshaping (columns first)

5 of 13

2/4/2014 2:52 PM

NumPy for IDL users Mathesaurus

http://mathesaurus.sourceforge.net/idl-numpy.html

a.flatten()

or

a.flatten(1)

Flatten to vector (by rows, like comics) Flatten to vector (by columns)

Shared data (slicing)


IDL Python b = a.copy() Description

Copy of a

Indexing and accessing elements (Python: slicing)


IDL a = [[ 11, 12, 13, 14 ], $ [ 21, 22, 23, 24 ], $ [ 31, 32, 33, 34 ]] a(2,1) a(*,0) a(0,*) Python a = array([[ 11, 12, 13, 14 ], [ 21, 22, 23, 24 ], [ 31, 32, 33, 34 ]]) a[1,2] a[0,] a[:,0] a.take([0,2]).take([0,3], axis=1) a(*,1:*) a[1:,] a[-2:,] a[::2,:] a[...,2] a.take([0,2,3],axis=1) a.diagonal(offset=0) Description

Input is a 3,4 array

Element 2,3 (row,col) First row First column Array as indices All, except first row Last two rows Strides: Every other row Third in last dimension (axis) Remove one column Diagonal

Assignment
IDL Python a[:,0] = 99 a[:,0] = array([99,98,97]) a>90 (a>90).choose(a,90) a.clip(min=None, max=90) a < 2 > 5 a.clip(min=2, max=5) Description

Clipping: Replace all elements over 90 Clip upper and lower values

Transpose and inverse


IDL transpose(a) Python a.conj().transpose() a.transpose() determ(a) invert(a) Description

or linalg.inv(a) or
linalg.det(a) linalg.pinv(a) norm(a)

hqr(elmhes(a))

linalg.eig(a)[0]

Transpose Non-conjugate transpose Determinant Inverse Pseudo-inverse Norms Eigenvalues

6 of 13

2/4/2014 2:52 PM

NumPy for IDL users Mathesaurus

http://mathesaurus.sourceforge.net/idl-numpy.html

svdc,A,w,U,V

linalg.svd(a) linalg.cholesky(a) linalg.eig(a)[1] rank(a)

Singular values Cholesky factorization Eigenvectors Rank

Sum
IDL total(a,2) total(a,1) total(a) Python a.sum(axis=0) a.sum(axis=1) a.sum() a.trace(offset=0) a.cumsum(axis=0) Description

Sum of each column Sum of each row Sum of all elements Sum along diagonal Cumulative sum (columns)

Sorting
IDL Python a = array([[4,3,2],[2,8,6], [1,4,7]]) a.ravel().sort() sort(a) a.sort(axis=0) a.sort(axis=1) a[a[:,0].argsort(),] a.ravel().argsort() a.argsort(axis=0) a.argsort(axis=1) Description

Example data Flat and sorted Sort each column Sort each row Sort rows (by first row) Sort, return indices Sort each column, return indices Sort each row, return indices

or

or msort(a)

Maximum and minimum


IDL max(a,DIMENSION=2) max(a,DIMENSION=1) max(a) Python Description

or amax(a [,axis=0]) a.max(1) or amax(a, axis=1) a.max() or


a.max(0) maximum(b,c) a.ptp(); a.ptp(0)

max in each column max in each row max in array pairwise max max-to-min range

Matrix manipulation
IDL reverse(a) reverse(a,2) rotate(a,1) Python Description

or a[:,::-1] flipud(a) or a[::-1,]


fliplr(a) rot90(a) kron(ones((2,3)),a) triu(a) tril(a)

Flip left-right Flip up-down Rotate 90 degrees Repeat matrix: [ a a a ; a a a ] Triangular, upper Triangular, lower

7 of 13

2/4/2014 2:52 PM

NumPy for IDL users Mathesaurus

http://mathesaurus.sourceforge.net/idl-numpy.html

Equivalents to "size"
IDL size(a) s=size(a) & s[1] n_elements(a) Python Description

or a.getshape() a.shape[1] or size(a, axis=1) a.size or size(a[, axis=None])


a.shape a.ndim a.nbytes

Matrix dimensions Number of columns Number of elements Number of dimensions Number of bytes used in memory

Matrix- and elementwise- multiplication


IDL Python a * b a # b Description

or multiply(a,b) or or

or b

## a

matrixmultiply(a,b) inner(a,b)

transpose(a) # b

a # b

outer(a,b) kron(a,b)

cramer(a,b)

linalg.solve(a,b)

vdot(a,b) cross(a,b)

Elementwise operations Matrix product (dot product) Inner matrix vector multiplication $a\cdot b$ Outer product Kronecker product Left matrix division, $b^{-1} {\cdot}a$ \newline (solve linear equations) Vector dot product Cross product

Find; conditional indexing


IDL Python a.ravel().nonzero() where(a NE 0) (i,j) = a.nonzero() (i,j) = where(a!=0) a(where(a NE 0)) v = a.compress((a!=0).flat) v = extract(a!=0,a) where(a GE 5.5) a(where(a GE 5.5)) (a>5.5).nonzero() a.compress((a>5.5).flat) where(a>5.5,0,a) a.put(2,indices) Description

Non-zero elements, indices Non-zero elements, array indices Vector of non-zero values Condition, indices Return values Zero out elements above 5.5 Replace values

or a

* (a>5.5)

Multi-way arrays
IDL Python a = array([[[1,2],[1,2]], [[3,4],[3,4]]]) a[0,...] Description

Define a 3-way array

File input and output

8 of 13

2/4/2014 2:52 PM

NumPy for IDL users Mathesaurus

http://mathesaurus.sourceforge.net/idl-numpy.html

IDL read()

Python f = fromfile("data.txt") f = load("data.txt")

Description

Reading from a file (2d) Reading from a file (2d) Reading fram a CSV file (2d) Writing to a file (2d) Writing to a file (1d) Reading from a file (1d)

read() x =

f = load("data.txt") f = load('data.csv',

read_ascii(data_start=1,delimiter=';') delimiter=';') save('data.csv', f, fmt='%.6f', delimiter=';') f.tofile(file='data.csv', format='%.6f', sep=';') f = fromfile(file='data.csv', sep=';')

Plotting Basic x-y plots


IDL plot, a plot, x(1,*), x(2,*) Python plot(a) plot(x[:,0],x[:,1],'o') plot(x1,y1,'bo', x2,y2,'go') plot, x1, y1 oplot, x2, y2 plot(x1,y1,'o') plot(x2,y2,'o') show() # as normal !p.multi(0,2,1) plot, x,y, line=1, psym=-1 subplot(211) plot(x,y,'ro-') Description

1d line plot 2d scatter plot Two graphs in one plot Overplotting: Add new plots to current subplots Plotting symbols and color

Axes and titles


IDL Python grid() figure(figsize=(6,6)) plot, x(1,*), x(2,*), xran=[0,10], yran=[0,5] plot, x,y, title='title', xtitle='x-axis', ytitle='y-axis' xyouts, 2,25, 'hello' text(2,25,'hello') axis([ 0, 10, 0, 5 ]) Description

Turn on grid lines 1:1 aspect ratio Set axes manually Axis labels and titles

Insert text

Log plots
IDL plot, x,y, /YLOG plot, x,y, Python Description

or plot_io, /XLOG or plot_oi,

x,y semilogy(a) x,y semilogx(a) loglog(a)

plot_oo, x,y

logarithmic y-axis logarithmic x-axis logarithmic x and y axes

9 of 13

2/4/2014 2:52 PM

NumPy for IDL users Mathesaurus

http://mathesaurus.sourceforge.net/idl-numpy.html

Filled plots and bar plots


IDL Python fill(t,s,'b', t,c,'g', alpha=0.2) Description

Filled plot

Functions
IDL Python x = arrayrange(0,40,.5) y = sin(x/3) - cos(x/5) plot(x,y, 'o') Description

Plot a function for given range

Polar plots
IDL Python theta = arange(0,2*pi,0.001) r = sin(2*theta) polar(theta, rho) Description

Histogram plots
IDL plot, histogram(randomn(5,1000)) Python Description

3d data Contour and image plots


IDL contour, z Python levels, colls = contour(Z, V, origin='lower', extent= (-3,3,-3,3)) clabel(colls, levels, inline=1, fmt='%1.1f', fontsize=10) contour, z, nlevels=7, /fill contour, z, nlevels=7, /overplot, /downhill contourf(Z, V, cmap=cm.gray, origin='lower', extent=(-3,3,-3,3)) tv, z loadct,0 im = imshow(Z, interpolation='bilinear', origin='lower', extent=(-3,3,-3,3)) # imshow() and contour() as above quiver() Description

Contour plot

Filled contour plot

Plot image data

Image with contours Direction field vectors

Perspective plots of surfaces over the x-y plane

10 of 13

2/4/2014 2:52 PM

NumPy for IDL users Mathesaurus

http://mathesaurus.sourceforge.net/idl-numpy.html

IDL

Python n=arrayrange(-2,2,.1) [x,y] = meshgrid(n,n) z = x*power(math.e,-x**2-y**2)

Description

surface, z shade_surf, z loadct,3

Mesh plot Surface plot

Scatter (cloud) plots


IDL Python Description

Save plot to a graphics file


IDL set_plot,'PS' device, file='foo.eps', /land plot x,y device,/close & set_plot,'win' savefig('foo.pdf') savefig('foo.svg') savefig('foo.png') Python savefig('foo.eps') Description

PostScript

PDF SVG (vector graphics for www) PNG (raster graphics)

Data analysis Set membership operators


IDL Python a = array([1,2,2,5,2]) b = array([2,3,4]) a = set([1,2,2,5,2]) b = set([2,3,4]) unique1d(a) unique(a) set(a) union1d(a,b) a.union(b) intersect1d(a) a.intersection(b) setdiff1d(a,b) a.difference(b) setxor1d(a,b) a.symmetric_difference(b) 2 in a setmember1d(2,a) contains(a,2) Description

Create sets

Set unique

Set union Set intersection Set difference Set exclusion True for set member

Statistics
11 of 13 2/4/2014 2:52 PM

NumPy for IDL users Mathesaurus

http://mathesaurus.sourceforge.net/idl-numpy.html

IDL mean(a)

Python a.mean(axis=0) mean(a [,axis=0])

Description

Average

median(a) stddev(a)

or median(a [,axis=0]) Median a.std(axis=0) or std(a Standard deviation


median(a) [,axis=0])

variance(a) correlate(x,y)

or var(a) correlate(x,y) or corrcoef(x,y)


a.var(axis=0) cov(x,y)

Variance Correlation coefficient Covariance

Interpolation and regression


IDL poly_fit(x,y,1) Python (a,b) = polyfit(x,y,1) plot(x,y,'o', x,a*x+b,'-') linalg.lstsq(x,y) polyfit(x,y,3) Description

Straight line fit Linear least squares $y = ax + b$ Polynomial fit

Non-linear methods Polynomials, root finding


IDL Python poly() Description

Polynomial roots() Find zeros of polynomial polyval(array([1,2,1,2]),arange(1,11)) Evaluate polynomial

Differential equations
IDL Python diff(x, n=1, axis=0) Description

Discrete difference function and approximate derivative

Fourier analysis
IDL fft(a) fft(a),/inverse convol() Python Description

or ifft(a) or
fft(a) convolve(x,y)

Fast fourier transform Inverse fourier transform Linear convolution

Symbolic algebra; calculus


IDL Python Description

Programming
IDL Python Description

12 of 13

2/4/2014 2:52 PM

NumPy for IDL users Mathesaurus

http://mathesaurus.sourceforge.net/idl-numpy.html

.idlbatch ;

.py # from pylab import * string="a=234" eval(string)

Script file extension Comment symbol (rest of line) Import library functions Eval

Loops
IDL for k=1,5 do print,k for k=1,5 do begin $ print, i &$ print, i*2 &$ end Python for i in range(1,6): print(i) for i in range(1,6): print(i) print(i*2) Description

for-statement Multiline for statements

Conditionals
IDL if 1 gt 0 then a=100 if 1 gt 0 then a=100 else a=0 a>0?a:0 Python if 1>0: a=100 Description

if-statement if-else-statement Ternary operator (if?true:false)

Debugging
IDL help print, a print a Python Description

List variables loaded into memory Print

Working directory and OS


IDL dir Python os.listdir(".") grep.grep("*.py") sd os.getcwd() Description

cd,'foo

or sd,'foo

os.chdir('foo') os.system('notepad') os.popen('notepad')

spawn,'notepad'

List files in directory List script files in directory Displays the current working directory Change working directory Invoke a System Command

Time-stamp: "2007-11-09T16:46:36 vidar" 2006 Vidar Bronken Gundersen, /mathesaurus.sf.net Permission is granted to copy, distribute and/or modify this document as long as the above attribution is retained.

13 of 13

2/4/2014 2:52 PM

You might also like