Вы находитесь на странице: 1из 13

13/5/2016

NumPy for IDL users

NumPy for IDL users


Help
IDL

Python

Description

help()

?help

help

?plotor man,'plot

help(plot)or ?plot

Browse help interactively


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

help(pylab)
demo

Searching available documentation


IDL

Python

Description

help(); modules [Numeric]

List available packages


Locate functions

help(plot)

Using interactively
IDL

Python

idlde

ipython -pylab

@"foo.idlbatch"or .run

Description

Start session
TAB
Auto completion
execfile('foo.py')or run foo.pyRun code from le

'foo.pro'
help,/rec

hist -n

journal,'IDLhistory'
exitor CTRL-D

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

Command history
Save command history
End session

Operators
IDL Python Description

Arithmetic operators
IDL

Python

Description

a=1 & b=1

a=1; b=1

a+b

a + bor add(a,b)

a-b

a - bor subtract(a,b)

a*b

a * bor multiply(a,b)

a/b

a / bor divide(a,b)

a^b

a ** b
power(a,b)

Assignment; dening a number


Addition
Subtraction
Multiplication
Division
Power, $a^b$

http://www.astro.umd.edu/~mbk/idl-numpy.html

1/13

13/5/2016

NumPy for IDL users

pow(a,b)
a MOD b

a%b

Remainder

remainder(a,b)
fmod(a,b)
++aor a+=1
a++
a+=1

a+=bor add(a,b,a)

Increment, return new value


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

Relational operators
IDL

Python

Description

a eq b

a == bor equal(a,b)

a lt b

a < bor less(a,b)

a gt b

a > bor greater(a,b)

a le b

a <= bor less_equal(a,b)

a ge b

a >= bor greater_equal(a,b)

a ne b

a != bor not_equal(a,b)

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

Logical operators
IDL

Python

Description

a and b

Short-circuit logical AND


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

a or b
a and b

logical_and(a,b)or a and b

a or b

logical_or(a,b)or a or b

a xor b

logical_xor(a,b)

not a

logical_not(a)or not a

root and logarithm


IDL

Python

Description

sqrt(a)

math.sqrt(a)

alog(a)

math.log(a)

alog10(a)

math.log10(a)

math.exp(a)

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

IDL

Python

Description

round(a)

around(a)or math.round(a)

ceil(a)

ceil(a)

floor(a)

floor(a)

Round
Round up
Round down
Round towards zero

math.log(a, 2)
exp(a)

Round off

fix(a)

http://www.astro.umd.edu/~mbk/idl-numpy.html

2/13

13/5/2016

NumPy for IDL users

Mathematical constants
IDL

Python

Description

!pi

math.pi

exp(1)

math.eor math.exp(1)

$\pi=3.141592$
$e=2.718281$

Missing values; IEEE-754 oating point status ags


IDL

Python

Description

nan

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

inf
plus_inf
minus_inf
plus_zero
minus_zero

Complex numbers
IDL

Python

Description

complex(0,1)

z = 1j

z = complex(3,4)

z = 3+4jor z = complex(3,4)

abs(z)

abs(3+4j)

real_part(z)

z.real

imaginary(z)

z.imag

conj(z)

z.conj(); z.conjugate()

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

Trigonometry
IDL

Python

Description

atan2(b,a)

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

hypot(x,y)

Generate random numbers


IDL

Python

Description

randomu(seed, 10)

random.random((10,))
random.uniform((10,))

Uniform distribution

2+5*randomu(seed, 10)

random.uniform(2,7,(10,))

randomu(seed,[6,6])

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

randomn(seed, 10)

random.standard_normal((10,))

Uniform: Numbers between 2


and 7
Uniform: 6,6 array
Normal distribution

Vectors
IDL

Python

Description

a = [2, 3, 4, 5]

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

Row vector, $1 \times n$matrix

http://www.astro.umd.edu/~mbk/idl-numpy.html

3/13

13/5/2016

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

NumPy for IDL users

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

Column vector, $m \times 1$matrix

r_[1:10,'c']

Sequences
IDL

Python

Description

indgen(10)+1
dindgen(10)+1

arange(1,11, dtype=Float)
range(1,11)

1,2,3, ... ,10

dindgen(10)

arange(10.)

indgen(4)*3+1

arange(1,11,3)

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

arange(10,0,-1)
arange(10,0,-3)
linspace(1,10,7)
reverse(a)

a[::-1]or
a.fill(3), a[:] = 3

Concatenation (vectors)
IDL

Python

Description

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

concatenate((a,a))

Concatenate two vectors

[indgen(3)+1,a]

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

Repeating
IDL

Python

Description

concatenate((a,a))

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

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

Miss those elements out


IDL

Python

Description

a[1:]

miss the rst element


last element
last two elements

a[-1]
a[-2:]

Maximum and minimum


IDL

Python

Description

maximum(a,b)

pairwise max
max of all values in two vectors

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

http://www.astro.umd.edu/~mbk/idl-numpy.html

4/13

13/5/2016

NumPy for IDL users

Vector multiplication
IDL

Python

Description

a*a

Multiply two vectors


Vector cross product, $u \times v$
Vector dot product, $u \cdot v$

crossp(u,v)
dot(u,v)

Matrices
IDL

Python

Description

a = [[2,3],[4,5]]

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

Dene a matrix

Concatenation (matrices); rbind and cbind


IDL

Python

Description

concatenate((a,b), axis=0)

Bind rows

vstack((a,b))
concatenate((a,b), axis=1)
hstack((a,b))

Bind columns

Bind slices (three-way


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

vstack((r_[1:5],r_[1:5]))

Array creation
IDL

Python

Description

dblarr(3,5)

zeros((3,5),Float)

intarr(3,5)

zeros((3,5))

dblarr(3,5)+1

ones((3,5),Float)

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

intarr(3,5)+9
identity(3)

identity(3)

diag_matrix([4,5,6])

diag((4,5,6))
a = empty((3,3))

Reshape and atten matrices


IDL

Python

Description

reform(a,2,3)

arange(1,7).reshape(2,-1)

Reshaping (rows rst)

a.setshape(2,3)
arange(1,7).reshape(-1,2).transpose()Reshaping
a.flatten()or
a.flatten(1)

http://www.astro.umd.edu/~mbk/idl-numpy.html

(columns rst)
Flatten to vector (by rows,
like comics)
Flatten to vector (by
columns)
5/13

13/5/2016

NumPy for IDL users

Shared data (slicing)


IDL

Python

Description

b = a.copy()

Copy of a

Indexing and accessing elements (Python: slicing)


IDL

Python

Description

a = [[ 11, 12, 13, 14 ], $


[ 21, 22, 23, 24 ], $
[ 31, 32, 33, 34 ]]

a = array([[ 11, 12, 13, 14 ],


[ 21, 22, 23, 24 ],
[ 31, 32, 33, 34 ]])

Input is a 3,4 array

a(2,1)

a[1,2]

a(*,0)
a(0,*)

a(*,1:*)

Element 2,3 (row,col)


a[0,]
First row
a[:,0]
First column
a.take([0,2]).take([0,3], axis=1) Array as indices
a[1:,]
All, except rst row
a[-2:,]
Last two rows
a[::2,:]
Strides: Every other row
a[...,2]
Third in last dimension (axis)
a.take([0,2,3],axis=1)
Remove one column
a.diagonal(offset=0)
Diagonal

Assignment
IDL

Python

Description

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)

Clipping: Replace all elements


over 90
Clip upper and lower values

Transpose and inverse


IDL

Python

Description

transpose(a)

a.conj().transpose()

Transpose
Non-conjugate transpose
Determinant
Inverse
Pseudo-inverse
Norms
Eigenvalues
Singular values
Cholesky factorization
Eigenvectors
Rank

a.transpose()
determ(a)

linalg.det(a)or

invert(a)

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

hqr(elmhes(a))

linalg.eig(a)[0]

svdc,A,w,U,V

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

http://www.astro.umd.edu/~mbk/idl-numpy.html

6/13

13/5/2016

NumPy for IDL users

Sum
IDL

Python

Description

total(a,2)

a.sum(axis=0)

total(a,1)

a.sum(axis=1)

total(a)

a.sum()

a.cumsum(axis=0)

Sum of each column


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

Python

Description

a = array([[4,3,2],[2,8,6],

Example data

a.trace(offset=0)

Sorting
IDL

[1,4,7]])
a.ravel().sort()or
sort(a)

a.sort(axis=0)or msort(a)
a.sort(axis=1)
a[a[:,0].argsort(),]
a.ravel().argsort()
a.argsort(axis=0)
a.argsort(axis=1)

Flat and sorted


Sort each column
Sort each row
Sort rows (by rst row)
Sort, return indices
Sort each column, return indices
Sort each row, return indices

Maximum and minimum


IDL

Python

Description

max(a,DIMENSION=2)

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

max(a,DIMENSION=1)

a.max(1)or amax(a, axis=1)

max(a)

a.max()or

max in each column


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

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

Matrix manipulation
IDL

Python

Description

reverse(a)

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

reverse(a,2)

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

rotate(a,1)

rot90(a)

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

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

Equivalents to "size"
IDL

Python

Description

size(a)

a.shapeor a.getshape()

s=size(a) & s[1]

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

Matrix dimensions
Number of columns

http://www.astro.umd.edu/~mbk/idl-numpy.html

7/13

13/5/2016

n_elements(a)

NumPy for IDL users

a.sizeor size(a[, axis=None])


a.ndim
a.nbytes

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

Matrix- and elementwise- multiplication


IDL

Python

Description

a * bor multiply(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

a # bor b ## a

matrixmultiply(a,b)

transpose(a) # b

inner(a,b)or

a#b

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

cramer(a,b)

linalg.solve(a,b)

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

Find; conditional indexing


IDL

Python

Description

a.ravel().nonzero()

Non-zero elements, indices


Non-zero elements, array indices

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)

Vector of non-zero values

where(a GE 5.5)

(a>5.5).nonzero()

a(where(a GE 5.5))

a.compress((a>5.5).flat)

Condition, indices
Return values
Zero out elements above 5.5
Replace values

where(a>5.5,0,a)or a * (a>5.5)
a.put(2,indices)

Multi-way arrays
IDL

Python

Description

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

Dene a 3-way array

a[0,...]

File input and output


IDL

Python

Description

read()

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

Reading from a le (2d)

read()

f = load("data.txt")

Reading from a le (2d)


Reading fram a CSV le
(2d)

x=
f = load('data.csv',
read_ascii(data_start=1,delimiter=';')delimiter=';')
http://www.astro.umd.edu/~mbk/idl-numpy.html

8/13

13/5/2016

NumPy for IDL users

save('data.csv', f,
fmt='%.6f', delimiter=';')

Writing to a le (2d)

f.tofile(file='data.csv',
format='%.6f', sep=';')

Writing to a le (1d)

f = fromfile(file='data.csv',
sep=';')

Reading from a le (1d)

Plotting
Basic x-y plots
IDL

Python

Description

plot, a

plot(a)

plot, x(1,*), x(2,*)

plot(x[:,0],x[:,1],'o')

1d line plot
2d scatter plot
Two graphs in one plot
Overplotting: Add new plots to
current

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)

subplot(211)

plot, x,y, line=1, psym=-1

plot(x,y,'ro-')

subplots
Plotting symbols and color

Axes and titles


IDL

Python

Description

grid()

Turn on grid lines


1:1 aspect ratio
Set axes manually

figure(figsize=(6,6))
plot, x(1,*), x(2,*),
xran=[0,10], yran=[0,5]

axis([ 0, 10, 0, 5 ])

Axis labels and titles

plot, x,y, title='title',


xtitle='x-axis', ytitle='yaxis'
xyouts, 2,25, 'hello'

text(2,25,'hello')

Insert text

Log plots
IDL

Python

Description

plot, x,y, /YLOGor plot_io,


x,y

semilogy(a)

logarithmic y-axis

plot, x,y, /XLOGor plot_oi,


x,y

semilogx(a)

logarithmic x-axis

plot_oo, x,y

loglog(a)

logarithmic x and y axes

Filled plots and bar plots


IDL

http://www.astro.umd.edu/~mbk/idl-numpy.html

Python

Description

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

Filled plot

9/13

13/5/2016

NumPy for IDL users

Functions
IDL

Python

Description

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

Plot a function for given range

Python

Description

Polar plots
IDL

theta = arange(0,2*pi,0.001)
r = sin(2*theta)
polar(theta, rho)

Histogram plots
IDL

Python

Description

plot, histogram(randomn(5,1000))

3d data
Contour and image plots
IDL

Python

Description

contour, z

levels, colls = contour(Z, V,


origin='lower', extent=
(-3,3,-3,3))
clabel(colls, levels, inline=1,

Contour plot

fmt='%1.1f', fontsize=10)
contour, z, nlevels=7, /fill contourf(Z, V,
contour, z, nlevels=7,
cmap=cm.gray,
/overplot, /downhill

origin='lower',
extent=(-3,3,-3,3))

tv, z

im = imshow(Z,

loadct,0

interpolation='bilinear',
origin='lower',
extent=(-3,3,-3,3))

Filled contour plot

Plot image data

# imshow() and contour() as above Image


quiver()

with contours
Direction eld vectors

Perspective plots of surfaces over the x-y plane


IDL

Python

Description

n=arrayrange(-2,2,.1)
[x,y] = meshgrid(n,n)
z = x*power(math.e,-x**2-y**2)
surface, z
shade_surf, z
loadct,3
http://www.astro.umd.edu/~mbk/idl-numpy.html

Mesh plot
Surface plot
10/13

13/5/2016

NumPy for IDL users

Scatter (cloud) plots


IDL Python Description

Save plot to a graphics le


IDL

Python

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

Description

PostScript

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

Data analysis
Set membership operators
IDL

Python

Description

a = array([1,2,2,5,2])

Create sets

b = array([2,3,4])
a = set([1,2,2,5,2])
b = set([2,3,4])
unique1d(a)
unique(a)

Set unique

set(a)
union1d(a,b)
a.union(b)

Set union

intersect1d(a)

Set intersection

a.intersection(b)
setdiff1d(a,b)
a.difference(b)

Set difference

setxor1d(a,b)

Set exclusion

a.symmetric_difference(b)
2 in a
setmember1d(2,a)

True for set member

contains(a,2)

Statistics
IDL

Python

Description

mean(a)

a.mean(axis=0)

Average

mean(a [,axis=0])
median(a)

median(a)or median(a
[,axis=0])

Median

stddev(a)

a.std(axis=0)or std(a

Standard deviation

[,axis=0])
http://www.astro.umd.edu/~mbk/idl-numpy.html

11/13

13/5/2016

NumPy for IDL users

a.var(axis=0)or var(a)

Variance
correlate(x,y)or corrcoef(x,y) Correlation coefcient
cov(x,y)
Covariance

variance(a)
correlate(x,y)

Interpolation and regression


IDL

Python

Description

poly_fit(x,y,1)

(a,b) = polyfit(x,y,1)

Straight line t

plot(x,y,'o', x,a*x+b,'-')
linalg.lstsq(x,y)
polyfit(x,y,3)

Linear least squares $y = ax + b$


Polynomial t

Non-linear methods
Polynomials, root nding
IDL

Python

Description

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

Differential equations
IDL

Python

Description

diff(x, n=1, axis=0)

Discrete difference function and


approximate derivative

Fourier analysis
IDL

Python

Description

fft(a)

fft(a)or

fft(a),/inverse

ifft(a)or

convol()

convolve(x,y)

Fast fourier transform


Inverse fourier transform
Linear convolution

Symbolic algebra; calculus


IDL Python Description

Programming
IDL

Python

Description

.idlbatch

.py

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

from pylab import *


string="a=234"
eval(string)

http://www.astro.umd.edu/~mbk/idl-numpy.html

12/13

13/5/2016

NumPy for IDL users

Loops
IDL

Python

Description

for k=1,5 do print,k

for i in range(1,6): print(i)

for k=1,5 do begin $

for i in range(1,6):

for-statement
Multiline for statements

print, i &$
print, i*2 &$

print(i)
print(i*2)

end

Conditionals
IDL

Python

Description

if 1 gt 0 then a=100

if 1>0: a=100

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

Python

Description

print a

List variables loaded into memory


Print

if 1 gt 0 then a=100 else a=0


a>0?a:0

Debugging
IDL
help
print, a

Working directory and OS


IDL

Python

Description

dir

os.listdir(".")

List les in directory


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

glob.glob("*.py")
sd

os.getwd()

cd,'fooor sd,'foo

os.chdir('foo')

spawn,'notepad'

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

Slightly modified (mbk) from:


Vidar Bronken Gundersen /mathesaurus.sf.net, content is licensed under Creative Commons

http://www.astro.umd.edu/~mbk/idl-numpy.html

13/13

Вам также может понравиться