In [62]:
import numpy as np
In [63]:
a = np.array([1, 2, 3, 4, 5], float)
a
Out[63]:
In [64]:
b = np.array([9, 8, 9], int)
print(b.dtype)
In [65]:
print(a[2:]) # all elements after the 2nd
print(a[-1]) # last element
print(a[2:4]) # slice 3rd to 4th
print(a[::2]) # every second element
a[0] = 5
print(a)
In [66]:
# iteration
for elem in a:
print(elem)
In [67]:
A = np.array([[1,2,3], [4,5,6], [7,8,9]])
A
Out[67]:
In [68]:
print(A[0, 0]) # access single element
print(A[2, :]) # access 3rd row
print(A[:, 0]) # access first column
print(A[::2, :]) # get every second row
In [69]:
a = np.array(range(15))
print(a[1:10:2]) # every second elemtn from second to 10th
a[1::2] = 0 # set every second element to zero
print(a)
In [38]:
print(len(A)) # length of 1st dimension
print(A.shape) # shape of the arrays
In [39]:
print(2 in A)
print(13 in A)
In [70]:
c = np.array([1, 2, 3, 4, 5, 6])
print(c)
c.reshape((3, 2)) # reshape takes a dimension tuple as input (#rows,#cols)
Out[70]:
In [71]:
a = np.array([1, 2, 3])
b = a
c = a.copy()
a[0] = 6
print(a)
print(b)
print(c)
In [13]:
# convert to python list
a.tolist()
# fill up with new value
a.fill(12)
print(A)
print(A.transpose()) # transpose matrix
print(A.T) # same as A.transpose()
In [72]:
# concatenate arrays
B = A.transpose()
print(np.concatenate((A, B))) # concatenate vertically
print(np.concatenate((A, B), axis=1)) # concatenate horizontally
In [15]:
# equally spaced values within an interval: arange( start, stop, step )
np.arange(0, 5, 0.1)
Out[15]:
In [73]:
# alternative version: linspace(start, stop, no_points)
np.linspace(0, 5, 50)
Out[73]:
In [74]:
# generate 1 or 0-arrays
print(np.ones((2, 3)))
print(np.zeros((3, 4)))
In [43]:
# construct an array with a similar shape to another one
np.zeros_like(A)
Out[43]:
In [44]:
# identity matrix
Id = np.identity(4)
Id
Out[44]:
In [75]:
A = np.array([[1, 2], [6, 7]])
np.linalg.det(A) # determinant
np.linalg.eig(A) # eigenvalues and eigenvectors
np.linalg.inv(A) # matrix inverse
np.linalg.svd(A) # singular value decomposition
Out[75]:
In [46]:
A = np.array([[1, 2], [3, 4]])
B = np.array([[0, 1], [1, 0]])
A + B
A - B
A * B
B / A
A ** B
Out[46]:
In [45]:
A = np.ones((3, 3))
c = np.array([1, 2, 3])
# per default arrays are added row-wise
A + c
# like this col-wise
A + c[:, np.newaxis]
Out[45]:
In [48]:
# element-wise functions
np.sqrt(a) # square root
np.sign(a) # sign
np.log(a) # natural logarithm
np.log10(a) # decadic logarithm
np.exp(a) #exponential
np.sin(a) # trigonometric (also cos, tan, arcsin, arccos, arctan)
# non-element-wise
a.sum() # sum of all elements
a.prod() # product of all elements
a.mean() # mean
a.var() # variance
a.std() # standard deviation
a.max() # maximum
a.min() # minimum
a.sort()
np.unique([1, 1, 3, 3, 5]) # get unique elements
Out[48]:
In [49]:
A = np.array([[0, 1], [1, 0]])
v = np.array([6, 7])
np.dot(A, v) # matrix product
Out[49]:
In [50]:
a = np.array([1, 6, 3, 4, 9, 6, 7, 3, 2, 4, 5])
a[a > 4] # get all elements larger than 4
a[np.logical_and(a > 4, a < 12)]
# acessing via index
indices = [1, 3]
a[indices]
Out[50]:
Scipy is a collection of useful scientific algorithms
In [51]:
import scipy as sp
import scipy.optimize
In [52]:
from matplotlib import pyplot as plt
plt.style.use('ggplot')
%matplotlib inline
In [76]:
# define a function
def myfunc(x):
return (3 + x) * (3 - x) * -12
# minimize using scipy
sp.optimize.minimize_scalar(myfunc)
Out[76]:
In [54]:
# plot the function
x = np.arange(-100, 100, 1)
plt.plot(x, myfunc(x))
Out[54]:
Consider a growing bacterial population with a doubling time of 2 hours
this means that the growth rate is $$ k_g = \frac {ln( 2 )} {2} = 0.34657359027997264 $$
and the growth model: $$ \frac {dx} {dt} = k_g \cdot x $$
lets integrate this ODE using scipy.integrate.odeint
In [57]:
import scipy.integrate
k_g = np.log(2) / 2
x0 = 1e-5
time = np.arange(0, 10, 1)
def dxdt(x, t):
return k_g * x
result = scipy.integrate.odeint(dxdt, x0, time)
plt.plot(time, result)
Out[57]:
In [58]:
exact = x0 * np.exp(k_g * time)
exact - result.T
plt.plot(time, (exact - result.T).T)
Out[58]:
In [ ]: