Showing posts with label Py. Show all posts
Showing posts with label Py. Show all posts

Thursday, April 23, 2015

py41. Linear Rotation

We can use the Rotation matrix to rotate any line.


Here a line (y=2x+1) is rotated by 30 deg counter clockwise.


Since we don't specify the number of points in linspace, it uses the default num of 50.

# ex41.py
from __future__ import division, print_function
import numpy as np
from numpy import sin, cos, pi
import matplotlib.pyplot as plt
print('Original line: y=5x+1')
print('Rotation matrix: 30 deg ccw (+pi/6)')
ang = pi/6
R = np.array([[cos(ang),-sin(ang)],[sin(ang),cos(ang)]])
print('R (pi/6) =\n',R)
x = np.linspace(-2,2)
xyR = [R.dot([xv,5*xv+1]) for xv in x]
xR = [xv[0] for xv in xyR]
yR = [xv[1] for xv in xyR]
plt.plot(x,5*x+1,'r')
plt.plot(xR,yR,'b')
plt.title("x,y - Red, x',y' - Blue for R(pi/6)")
plt.xlabel("x,x'")
plt.ylabel("y,y'")
plt.xlim((-2,2))
plt.ylim((-2,2))
plt.show()

#    Original line: y=5x+1
#    Rotation matrix: 30 deg ccw (+pi/6)
#    R (pi/6) =
#     [[ 0.8660254 -0.5      ]
#     [ 0.5        0.8660254]]

Output:

py40. Matrix operations in Python

We can use numpy.matrix to create matrices, rather than numpy.array. With numpy.array, the * operation is element-wise multiplication. However, with numpy.matrix, the * operation is real matrix multiplication. With numpy.array, we can always do real matrix multiplication with numpy.dot function.


The function numpy.trace finds the trace of a matrix, which is the sum of the diagonal.

# ex40.py
from __future__ import division, print_function
import numpy as np
A = np.matrix([[1,5,1],[2,-1,6],[1,0,3]])
print('A = \n',A)
B = np.matrix([[2,3,0],[3,-1,7],[4,8,9]])
print('B = \n',B)
print('5*A-10*B+3*A*B =\n',5*A-10*B+3*A*B)
print('trace(A*B)=',np.trace(A*B))
print('trace(B*A)=',np.trace(B*A))

#    A = 
#     [[ 1  5  1]
#     [ 2 -1  6]
#     [ 1  0  3]]
#    B = 
#     [[ 2  3  0]
#     [ 3 -1  7]
#     [ 4  8  9]]
#    5*A-10*B+3*A*B =
#     [[ 48  13 137]
#     [ 55 170 101]
#     [  7   1   6]]
#    trace(A*B)= 103
#    trace(B*A)= 103

py39. Matrix inversion in Python

The function numpy.linalg.inv can be used to find the inverse of matrix.


We find x in the linear equation (Ax=b) using inversion x=inv(A)*b and also with numpy.linalg.solve.

# ex39.py
from __future__ import print_function, division
import numpy as np
A = np.array([[1, 1, 1],[1, -1, 1], [3, 5, -1] ])
print('A =\n',A)
print('shape of A =',A.shape)
inverse = np.linalg.inv(A)
print('inverse of A\n', inverse)
b = np.array([1,0,2])
print('b =\n',b)
print('For Ax=b')
x = np.linalg.solve(A,b)
print('x = ',x)
print('inv(A)*b =',inverse.dot(b))

#A =
# [[ 1  1  1]
# [ 1 -1  1]
# [ 3  5 -1]]
#shape of A = (3, 3)
#inverse of A
# [[-0.5   0.75  0.25]
# [ 0.5  -0.5  -0.  ]
# [ 1.   -0.25 -0.25]]
#b =
# [1 0 2]
#For Ax=b
#x =  [ 0.   0.5  0.5]
#inv(A)*b = [ 0.   0.5  0.5]

Tuesday, April 21, 2015

py38. Numpy arrays

Numpy arrays contain data of one kind, specified by the dtype attribute, which can be changed with astype(), with the proper string identifier.


We can select values by slicing, giving a list of indices, or a logical expression.


The hstack and vstack functions can join arrays horizontally or vertically. The T attribute can be used to find the transpose of a numpy array. A 2D array will correspond to a matrix, however we also have a matrix class in numpy.

# ex38.py
from __future__ import print_function, division
import numpy as np
A = np.arange(5)
print('A =',A)
print('A.dtype =',A.dtype)
B = A.astype('float')
print('B =',B)
print('B.dtype =',B.dtype)
print('A[2:4] =',A[2:4])
print('A[[2,3]] =',A[[2,3]])
print('A[A==2 | A==3] =',A[(A==2) | (A==3)])
M1 = np.hstack((A,A,A))
print('M1 =',M1)
M2 = np.vstack((A,A,A))
print('M2 =',M2)
M3 = M2.T
print('M3 (transpose M2) =',M3)

#A = [0 1 2 3 4]
#A.dtype = int32
#B = [ 0.  1.  2.  3.  4.]
#B.dtype = float64
#A[2:4] = [2 3]
#A[[2,3]] = [2 3]
#A[A==2 | A==3] = [2 3]
#M1 = [0 1 2 3 4 0 1 2 3 4 0 1 2 3 4]
#M2 = [[0 1 2 3 4]
# [0 1 2 3 4]
# [0 1 2 3 4]]
#M3 (transpose M2) = [[0 0 0]
# [1 1 1]
# [2 2 2]
# [3 3 3]
# [4 4 4]]

Tuesday, March 17, 2015

py37. split in Python

We have an input tuple of strings with two values separated by ':'. The value on the left is a string, whereas the value on the right is an integer.


We want to get a list of strings for the value that go before ':'.


We want to get an list of integers for the values that go after ':'.


We use list comprehensions to get the lists.


In addition, we create a combined list, with the values extracted from the input sequence, returned as a list of 2-length tuples. The split method of a string object is used. Notice we have to write the string, then a period to get any method or attributes. This leads to better management of the global namespace. For the split method we give the string to split as well as the split character.

# ex37.py
from __future__ import print_function
chr_vec = "time:30","pos:45","loc:5"
first_vec = [c.split(":")[0] for c in chr_vec]
second_vec = [int(c.split(":")[1]) for c in chr_vec]
combined_vec = [(c.split(":")[0],
                 int(c.split(":")[1])) for c in chr_vec]
print("original: ", chr_vec)
print("first_vec = ", first_vec)
print("second_vec = ", second_vec)
print("combined_vec = ", combined_vec)
#original:  ('time:30', 'pos:45', 'loc:5')
#first_vec =  ['time', 'pos', 'loc']
#second_vec =  [30, 45, 5]
#combined_vec =  [('time', 30), ('pos', 45), ('loc', 5)]

Friday, March 13, 2015

py36. Drawing Polygons in Python

To draw polygons, we have to give vertices as we loop over the polygon counterclockwise.


We use a curve with roots of -1,0,+1. We divide the x-axis based on these roots (will become 4 shaded regions).


Using list comprehensions we go make loops in x_1, x_2, x_3 and x_4, the four divisions of x that we chose.

# ex36.py

from __future__ import print_function, division
import numpy as np
import matplotlib.pyplot as plt

def y(x):
    return x**3 - x

x = np.arange(-1.5,1.51,.01)
tol = 0.01
    
x_1 = x[(x >= -1.5) & (x <= (-1+tol))]
x_2 = x[(x >= -1) & (x <= (0+tol))]
x_3 = x[(x >= 0) & (x <= (1+tol))]
x_4 = x[(x >= 1) & (x <= (1.5+tol))]

fig = plt.figure()
ax = fig.add_subplot(111) 
ax.plot(x,y(x),'b')
ax.axhline(0, color = 'm')
plt.xlim(-1.5,1.5)
plt.xlabel('x')
plt.ylabel('y(x)')
plt.title('y(x) = $x^3$ - x')

# Counter clockwise loops
verts_left_to_right = [(xv,y(xv)) for xv in x_1]
verts_right_to_left = [(xv,0) for xv in np.flipud(x_1)]
verts = verts_left_to_right + verts_right_to_left
poly = plt.Polygon(verts, color = 'violet')
ax.add_patch(poly)

verts_left_to_right = [(xv,0) for xv in x_2]
verts_right_to_left = [(xv,y(xv)) for xv in np.flipud(x_2)]
verts = verts_left_to_right + verts_right_to_left
poly = plt.Polygon(verts, color = 'green')
ax.add_patch(poly)

verts_left_to_right = [(xv,y(xv)) for xv in x_3]
verts_right_to_left = [(xv,0) for xv in np.flipud(x_3)]
verts = verts_left_to_right + verts_right_to_left
poly = plt.Polygon(verts, color = 'red')
ax.add_patch(poly)

verts_left_to_right = [(xv,0) for xv in x_4]
verts_right_to_left = [(xv,y(xv)) for xv in np.flipud(x_4)]
verts = verts_left_to_right + verts_right_to_left
poly = plt.Polygon(verts, color = 'yellow')
ax.add_patch(poly)

plt.show()

Output:

Monday, March 9, 2015

py35. Fitting Data using Newton's method in Python

Test vectors, x and y, are created. x, the input, goes from 0 to 100 in steps of 1.


y, the output, corresponds to x/(25+x) with some added noise. This signal reaches about 0.8.


Now when using the Newton's method, we have a vector of length 101. Some of the values will be positive and some negative. The function fit finds the sum over all the terms. Finding the root of fit, will find the curve in the middle of the data points. We find the best fit x/(k+x). k has to be near 25. There are many functions for finding best fits in scipy.


In many cases, Newton's method will not converge such as when the y' keeps on changing sign. In those cases, you can always plot the function over a grid of points and then find an approximate local minima, and use that as the starting value in Newton's method (the argument x0).

# ex35.py
from __future__ import print_function, division
import numpy as np
import matplotlib.pyplot as plt

def fit(k):
    return sum(y-x/(k+x))
    
def newton(f, tol=1E-10, x0=1, N=50, h=0.2):
    for i in range(N):
        df_dx = (f(x0+h/2)-f(x0-h/2))/h
        x1 = x0 - f(x0)/df_dx
        error = abs(x1-x0)
        print("i = %d,x1 = %.4f, error = %.4e" % (i,x1,error))
        if error < tol: break
        x0 = x1
    return x1

print('Test data x and y')
x = np.arange(101)
r = 0.2*np.random.rand(len(x))-0.1
y = x/(25+x) + r
plt.xlabel('x')
plt.ylabel('y')
plt.title(r'Fitting y = x/($k_0$+x)')
k0 = newton(fit)
print('k0 =',k0)
plt.plot(x, y, 'b', x, x/(k0+x),'m')
plt.legend(('actual','fit'), loc = 4)
plt.show()

#Test data x and y
#i = 0,x1 = 11.2652, error = 1.0265e+01
#i = 1,x1 = 22.3195, error = 1.1054e+01
#i = 2,x1 = 25.9416, error = 3.6221e+00
#i = 3,x1 = 26.1740, error = 2.3239e-01
#i = 4,x1 = 26.1749, error = 8.3630e-04
#i = 5,x1 = 26.1749, error = 1.3040e-08
#i = 6,x1 = 26.1749, error = 3.9080e-14
#k0 = 26.1748507877

Output:

Sunday, March 8, 2015

py34. Newton's method in Python

Newton's method is based on the approximating a function with only its first Taylor Series term:


y(x+dx) = y(x) + dx y'(x)


We are interested in dx, which will result in y(x + dx) = 0.


0 = y(x) + dx y'(x).


-y(x) = dx y'(x).


dx = -y(x)/y'(x).


A function newton is written implementing this, and used to calculate cube root of 3. Later, we will use it for more complicated cases.

# ex34.py
from __future__ import print_function, division

def fit(x):
    return 3-x**3

def newton(f, tol=1E-10, x0=1, N=50, h=0.2):
    for i in range(N):
        df_dx = (f(x0+h/2)-f(x0-h/2))/h
        x1 = x0 - f(x0)/df_dx
        error = abs(x1-x0)
        print("i = %d,x1 = %.4f, error = %.4e" % (i,x1,error))
        if error < tol: break
        x0 = x1
    return x1

cube_root_3 = newton(fit)
print('cube_root_3 =',cube_root_3,
      '\nfit(cube_root_3) = ',fit(cube_root_3))
#i = 0,x1 = 1.6645, error = 6.6445e-01
#i = 1,x1 = 1.4708, error = 1.9363e-01
#i = 2,x1 = 1.4428, error = 2.7982e-02
#i = 3,x1 = 1.4423, error = 5.9354e-04
#i = 4,x1 = 1.4422, error = 1.1936e-06
#i = 5,x1 = 1.4422, error = 1.9106e-09
#i = 6,x1 = 1.4422, error = 3.0567e-12
#cube_root_3 = 1.44224957031 
#fit(cube_root_3) =  -3.15303338994e-14

Friday, March 6, 2015

py33. Population with Harvesting in Python

A harvest term, H, is used in the equation of the population, which is:


dN/dt = rN(1-N/K) - H


Steady-state solutions can be found from the roots of equation above, after setting dN/dt equal to zero. We find the roots using numpy.roots function.

# ex33.py
from __future__ import print_function, division
import numpy as np
import matplotlib.pyplot as plt

r = .10 # growth rate / yr
K = 100000 # carrying capacity
t = 100 # number of years
H = 1600 # Harvesting / yr
num = np.zeros(t+1)
num0 = np.zeros(t+1)
num[0] = 40000
num0[0] = 40000
for i in range(t):
    num[i+1] = num[i]+r*num[i]*(1-num[i]/K)-H
    num0[i+1] = num0[i]+r*num0[i]*(1-num0[i]/K)
sol = np.roots([r/K,-r,H])
print('\nSolutions are %.0fk and %.0fk.' %
      (sol[0]/1000,sol[1]/1000))
mStr = ("Growth rate: %.2f,"
        "Carrying Capacity: %dk"
        "\nHarvesting %d")
tStr = r,K/1000,H
main =  mStr % tStr
plt.plot(range(t+1),num/1000, 'b',
         range(t+1),num0/1000,'m')
plt.ylim(38,102)
plt.xlabel('Year')
plt.ylabel('Number (Thousands)')
plt.title(main)
plt.text(70, 84, '80K (H = %d)' % H)
plt.text(70, 97, '100K (H = 0)')

#Solutions are 80k and 20k.

Output:

py32. Logistic Growth in Python

Logistic growth of fisheries, or other populations, will go towards a Carrying Capacity. The growth will start exponentially and is S-shaped.


For a specific rate of growth, and Carrying Capacity, the Population is shown.


The vertical line shows the maximum derivative, that is where the maximum growth occurs.

# ex32.py
from __future__ import print_function, division
import numpy as np
import matplotlib.pyplot as plt

r = .25 # growth rate / yr
K = 100 # carrying capacity
t = 40 # number of years
num = np.zeros(t+1)
num[0] = 1
for i in range(t):
    num[i+1] = num[i]+r*num[i]*(1-num[i]/K)
plt.plot(range(t+1),num, 'b')
plt.xlabel('Year')
plt.ylabel('Number')
plt.title('Growth rate: 0.25, Carrying Capacity = 100')
plt.axvline(np.argmax(np.diff(num)),  color = 'k'  )
plt.show()

Output:

py31. Reading a json file in Python

Using the example json file from wikipedia.


The function json.load is used.


A dictionary is read and we can print what are the components of the dictionary. Since a Python dictionary does have any order, it does not list in the order that they are read from the file.


Since len() may not be applied to all types of data, the length is only printed if len() does not return an exception, in which case, it does nothing.

# ex31.py
from __future__ import print_function, division
import json
with open("ex31data.json") as f:
    data = json.load(f)
for k in data:
    print('\n', k, sep='')
    print('type:',type(data[k]))
    try: 
        print('length:',len(data[k]))
    except: pass
    
print("\ndata['phoneNumber']")
for i in data['phoneNumber']:
    print(i)

#firstName
#type: <type 'unicode'>
#length: 4
#
#lastName
#type: <type 'unicode'>
#length: 5
#
#age
#type: <type 'int'>
#
#address
#type: <type 'dict'>
#length: 4
#
#phoneNumber
#type: <type 'list'>
#length: 2
#
#gender
#type: <type 'dict'>
#length: 1
#
#data['phoneNumber']
#{u'type': u'home', u'number': u'212 555-1234'}
#{u'type': u'fax', u'number': u'646 555-4567'}

Tuesday, March 3, 2015

py30. Reading and parsing XML document in Python

We will use a test xml file, from python documentation country_data.xml.


The module bs4, Beautiful Soup 4, is used to parse the document. If this module is not installed, you will have to install it using the methods described at the their website, such as pip. If using a distribution like Anaconda, use the pip inside the distribution. It is possible to use other modules as described in the python link.


The name of the country, the year, as well as the neighbours are returned for all 3 countries in document.

# ex30.py
from __future__ import print_function, division
from bs4 import BeautifulSoup
doc = BeautifulSoup(open('ex30data.xml'),"xml")
country = doc.findAll("country")
for c in country:
    print("\n",c.attrs['name'],sep = "")
    y = c.find('year')
    print('year :',y.text)
    n = c.findAll('neighbor')
    for i,ni in enumerate(n):
        print("neighbor",i, end=" ", sep=" : ")
        print(ni.attrs)
    
#Liechtenstein
#year : 2008
#neighbor : 0 {'direction': u'E', 'name': u'Austria'}
#neighbor : 1 {'direction': u'W', 'name': u'Switzerland'}
#
#Singapore
#year : 2011
#neighbor : 0 {'direction': u'N', 'name': u'Malaysia'}
#
#Panama
#year : 2011
#neighbor : 0 {'direction': u'W', 'name': u'Costa Rica'}
#neighbor : 1 {'direction': u'E', 'name': u'Colombia'}

Friday, February 27, 2015

py29. Discrete Cosine Transform in Python

The Discrete Cosine Transform (DCT) leads to a real transform, whereas the fft leads to a complex transform. The relevant equations are given, for example, at Wikipedia Type 2 is the dct and type 3 is idct. We have to convert these equations to a form for the fft and ifft.


The program below finds the DCT and inverse DCT using fft and ifft. For both fft and ifft, we have to solve a 2N problem. For example, for the DCT, x is joined with its reverse. Besides the fft and ifft, we have to add phase terms and proper scaling constants.


The example x is of length 16. We plot x and its DCT. The main code is run only if the file is ran directly, and not imported by other python programs.


For comparison, we use the dct and idct functions from scipy.fftpack module with aliases of sdct, and sidct.

# ex29.py

from __future__ import print_function, division
import numpy as np
from scipy.fftpack import dct as sdct, idct as sidct
from numpy.fft import fft, ifft
import matplotlib.pyplot as plt

def dct(X):
    x = np.concatenate([X,np.flipud(X)])
    N = 2*len(X)
    f0 = 1/np.sqrt(2*N)
    f1 = 1/np.sqrt(N)
    Y = fft(x)
    kin = np.arange(N)
    Mul = np.cos(np.pi/N*kin)-1j*np.sin(np.pi/N*kin)
    Y *= Mul
    Y *= f1
    Y[0] *= f0/f1
    return Y[:N/2].real

def idct(X):
    N = len(X)
    f0 = 1/np.sqrt(4*N)
    f1 = 1/np.sqrt(2*N)
    kin = np.arange(N)
    FTR = X*np.cos(.5*np.pi/N*kin)
    FTI = X*np.sin(.5*np.pi/N*kin)
    FTR /= f1
    FTI /= f1
    FTR[0] *= f1/f0
    FTI[0] *= f1/f0
    FTR1 = np.concatenate((FTR,np.zeros(1),np.flipud(FTR[1:])))
    FTI1 = np.concatenate((FTI,np.zeros(1),-1*np.flipud(FTI[1:])))
    y = ifft(FTR1+1j*FTI1)
    return y[:N].real

if __name__ == '__main__':
    x = np.array(range(4)+range(2,5)+range(10,1,-1))
    y = dct(x)
    y1 = sdct(x.astype('float'), norm = 'ortho')
    z = idct(y)
    z1 = sidct(y1, norm = 'ortho')
    err1 = (z-x).std()
    err2 = (z1-x).std()
    print ('err1 =',err1)
    print ('err2 =',err2)
    plt.plot(x,'ro--', markerfacecolor='w')
    plt.plot(y,'bo--', markerfacecolor='w')
    plt.xlabel('n')
    plt.ylabel('x,y')
    plt.title('x (red), y = dct(x) (blue)')
    plt.xlim(-.5,15.5)
    plt.show()

# err1 = 1.43874580946e-15
# err2 = 4.52626554495e-16

Output:

Thursday, February 26, 2015

py28. Fast Fourier Transform in Python

The Discrete Fourier Transform (DFT) is the pair of transforms for the transform and its inverse:


The Fast Fourier Transform (FFT) is the solution of DFT using an algorithm based on symmetry of equations.


We use the fft function from the numpy.fft module to solve for the transform of a 64-length numpy array. It returns a complex numpy array, dtype = 'complex', which is sent to ifft function in the same module. We compare it to the the result from dft and inverse dft. The result are the same, with errors on order of double-precision tolerance.

# ex28.py

from __future__ import print_function, division
import numpy as np
from numpy.fft import fft, ifft
from numpy import pi, exp
def dft(x, inverse = False):
    N = len(x)
    s,d = (1,N) if inverse else (-1,1)
    X = np.zeros(N, dtype='complex')
    for k in range(N):
        for n in range(N):
            X[k] += x[n]*exp(1j*s*2*pi*k*n/N)
    return X/d

x = np.array(range(32)+range(31,-1,-1))
y = fft(x)
y1 = dft(x)
z = ifft(y)
z1 = dft(y1,True)
xR = z.real
x1R = z1.real
error_fft = (x-xR).std()
error_dft = (x-x1R).std()
print("error_fft = %e\nerror_dft = %e" % (error_fft,error_dft))
# error_fft = 1.122558e-15
# error_dft = 1.060977e-13

py27. Cauchy Distribution in Python


The Cauchy Cumulative Distribution Function is:







We use this formula as well as scipy.stats.cauchy.cdf function in the plot, and the two lines are plotted with different linewidths.


# ex27.py
from __future__ import print_function, division
import matplotlib.pyplot as plt
from numpy import linspace, pi, arctan as atan
from scipy.stats import cauchy
N = 500
gamma = 2
x0 = 3
x = linspace(-5*gamma+x0,+5*gamma+x0,num = N)
y = 1/pi*atan((x-x0)/gamma) + 0.5
y1 = cauchy.cdf(x, loc = x0, scale = gamma)
title = 'Cauchy CDF, gamma = %.1f, and x0 = %.1f' % (gamma, x0)
plt.plot(x,y, 'k', lw = 10)
plt.plot(x,y1,'g', lw = 5)
plt.title(title)
plt.show()

Output:

Monday, February 23, 2015

py26. Magic Function in Python

Magic matrices have sum of all rows and sum of all columns equal to some number. In addition, the sum of the primary and secondary cross diagonal equal that number, called the magic number. The magic number is only dependent on size of matrix.


The program will solve magic matrices for odd size, such as 11 by 11 (N = 11).


For a magic matrix, such as a size of 11 by 11, we have elements from 1 to 11 square. The magic number is the mean of all elements from 1 to N square, multiplied by N.


We use the numpy.zeros function to create a N*N matrix and then loop, over the 2-dimensions, to get the individual elements, {1,2,3,...N^2}, into their correct positions. Magic matrices are not unique, there are many others, dependent on the algorithm, with the same sum property, however the magic number for a particular N is unique.


Lastly, we check all the relevant sums.

# ex26.py
from __future__ import print_function, division
import numpy as np

N = 11

magic_num = sum(range(1,N**2+1))/N

def mat(i,j):
    i = i % N
    j = j % N
    return i,j
    
A = np.zeros((N,N))
st = (N-1)/2,(N+1)/2

for k2 in range(N):
    st = st[0]+1,st[1]-1
    for k in range(N):
        A[mat(st[0]+k,st[1]+k)] = k+k2*N+1

A = A.astype('int')
AR = np.fliplr(A)
print('magic(%d) = \n%s' % (N,A))
print('\nmagic number = %d' % magic_num)
print('sum primary diag = %d' % sum(A.diagonal()))
print('sum secondary diag = %d' % sum(AR.diagonal()))
for k2 in range(N):
    print('sum row %d = %d' % (k2,sum(A[k2,:])))
    print('sum col %d = %d' % (k2,sum(A[:,k2])))

#magic(11) = 
#[[ 56 117  46 107  36  97  26  87  16  77   6]
# [  7  57 118  47 108  37  98  27  88  17  67]
# [ 68   8  58 119  48 109  38  99  28  78  18]
# [ 19  69   9  59 120  49 110  39  89  29  79]
# [ 80  20  70  10  60 121  50 100  40  90  30]
# [ 31  81  21  71  11  61 111  51 101  41  91]
# [ 92  32  82  22  72   1  62 112  52 102  42]
# [ 43  93  33  83  12  73   2  63 113  53 103]
# [104  44  94  23  84  13  74   3  64 114  54]
# [ 55 105  34  95  24  85  14  75   4  65 115]
# [116  45 106  35  96  25  86  15  76   5  66]]
#
#magic number = 671
#sum primary diag = 671
#sum secondary diag = 671
#sum row 0 = 671
#sum col 0 = 671
#sum row 1 = 671
#sum col 1 = 671
#sum row 2 = 671
#sum col 2 = 671
#sum row 3 = 671
#sum col 3 = 671
#sum row 4 = 671
#sum col 4 = 671
#sum row 5 = 671
#sum col 5 = 671
#sum row 6 = 671
#sum col 6 = 671
#sum row 7 = 671
#sum col 7 = 671
#sum row 8 = 671
#sum col 8 = 671
#sum row 9 = 671
#sum col 9 = 671
#sum row 10 = 671
#sum col 10 = 671

Saturday, February 21, 2015

py25. Gamma Distribution in Python

Like the Poisson and Exponential distribution, the Gamma distribution is also dependent on the exponential series.


Besides the calculation above, we can use the function scipy.stats.gamma.cdf

# ex25.py
from __future__ import print_function, division
import matplotlib.pyplot as plt
import numpy as np
from scipy.stats import gamma
# shape, scale parameters
k,s = 7,2

def get_num(x,kv):
    xp = x/s
    coeff = np.exp(-xp)
    if kv == 0: return coeff
    cv = xp/np.arange(1,kv+1)
    return coeff*np.prod(cv)

def gamma_dis(x, calc):
    dis_calc = np.zeros(len(x))
    for i in range(len(x)):
        S = [get_num(x[i],kv) for kv in range(k)]
        dis_calc[i] = 1 - sum(S)
    dis_R = gamma.cdf(x, k, scale = s)
    if calc: return dis_calc
    else: return dis_R

main = ('Gamma Cumulative Distribution Function'
        '\nShape = 7, Scale = 2')
x = np.arange(40, step = .1)
plt.plot(x, gamma_dis(x,False),'r')
plt.xlabel('x')
plt.ylabel('P')
plt.title(main)
plt.plot(x, gamma_dis(x,True), 'b')
plt.show()

Output:

Thursday, February 19, 2015

py24. Exponential Distribution in Python

The exponential distribution, gives probability of events in time, etc, which is usually denoted by x, given a rate of lambda. The Poisson distribution gives the number of events with a rate. Rate and time are reciprocal, so expected value of x is 1/lambda.


The exponential distribution cumulative density function, CDF, is:


P(X<=x) = 1 - exp(-lambda*x)


Three important x values are:.


x = 0. P(X<=0) = 0, as exp(0) = 1, number of probability at time 0 is 0, where the function starts.


x = 1/lambda. P(X<=1/lambda)= 0.632 as exp(-1) = 0.368, that is, we have a little less than 2/3 probability.


x = Infinity. P(X<=Infinity) = 1, as exp(-Infinity) = 0, since probability has to happen in some finite time.


The probability density function is the derivative with respect to x, lambda*exp(-lambda*x).


The function scipy.stats.expon.cdf is used for the exponential CDF. In the call to this function, we have to put the mean value: 1/lambda. Again, since lambda is a reserved word in Python, we used lamb_da in the example.

# ex24.py
from __future__ import print_function, division
import matplotlib.pyplot as plt
import numpy as np
from scipy.stats import expon

N = 1.1
x = np.arange(N+.01,step=.01)

def exp_dis(lamb_da, calc):
    dis_calc = 1 - np.exp(-lamb_da*x)
    dis_R = expon.cdf(x,scale = 1/lamb_da)
    if calc: return dis_calc
    else: return dis_R

c0 = 0.8
plt.plot(x,exp_dis(1, False), color = (0,1-c0,c0))
plt.xlabel('x')
plt.ylabel('p')
plt.title('Exponential Distribution (lambda = 9,7,5,3,1)')
plt.plot(x, [1-np.exp(-1)]*len(x), color = 'red')
for i in 3,5,7,9:
    c0 -= .1
    plt.plot(x,exp_dis(i, False),
         color = (0,1-c0,c0))
plt.show()         
err = exp_dis(9,True)-exp_dis(9,False)
print('err for lambda of 9 =', err.std())
# err for lambda of 9 = 3.03591780425e-17

Output:

Wednesday, February 18, 2015

py23. Poisson Distribution in Python

Given a rate of lambda for an event in some interval, the Poisson distribution finds k such events, in the same interval. We know that the expected value of k has to be lambda.


For a particular k, we have the formula lambda^k/factorial(k) multiplied by a normalization constant. We can rewrite lambda^k/factorial(k) as:


(lambda/k)*(lambda/(k-1))*(lambda/(k-2))*...*(lambda/2)*(lambda) for k not 0, and 1 for k equal to 0


The function get_num finds this value multiplied by the normalization constant, which is exp(-lambda). With the normalization, the total probability for all k is 1.


Besides calculating, we can use the scipy.stats.poisson.pmf function. Since lambda is a keyword in Python, it was written as lamb_da, in the example.

# ex23.py
from __future__ import print_function, division
import matplotlib.pyplot as plt
import numpy as np
from scipy.stats import poisson
N = 20
k = np.arange(0,N+1)

def get_num(lamb_da,k):
    coeff = np.exp(-lamb_da)
    if k==0: return coeff
    cv = lamb_da/np.arange(1,k+1)
    return coeff*np.prod(cv)
    

def pois(lamb_da, calc):
    dis_calc = np.array([get_num(lamb_da,i) for i in range(N+1)])
    dis_R = poisson.pmf(k,lamb_da)
    if calc: return dis_calc
    else: return dis_R

c0 = 0.8
pr = 0
st = ['o','v','^','s','d']
plt.plot(k,pois(1, False), st[pr] + '--', color = (0,1-c0,c0))
for i in 3,5,7,9:
    c0 -= .1
    pr = (i-1)//2
    plt.plot(k,pois(i, True), st[pr] + '--', color = (0,1-c0,c0))
    plt.xlabel('k')
    plt.ylabel('p')
    plt.title('Poisson Distribution (lambda = 1,3,5,7,9)')

err = pois(9,True) - pois(9,False)
print('err for lambda of 9 =', err.std())
# err for lambda of 9 = 9.4458398513e-17

Output:

py22. One Sample t-test in Python

A one-sample t-test is conducted over a range of mean values. The null hypothesis is that test mean is the true mean of the population.


The sample is of length 500 and is a random sample based on a standard normal distribution, which has a mean of 0. Thus, we expect values far from 0 will be rejected. For the normal sample, we use scipy.stats.norm.rvs function


If you uncomment the print() lines, you will get intermediate results. You can use the scipy.stats.ttest_1samp function or a calculation, based on the t-distribution. We have a two sided alternative hypotheses, that is, we sum over both tails. This is the default for ttest_1samp from scipy.stats module. The t distribution, from this module, is used but with the alias st.

# ex22.py
from __future__ import print_function, division
import matplotlib.pyplot as plt
import numpy as np
from scipy.stats import norm, ttest_1samp, t as st
N = 500
mu = np.arange(-.2,+.201,.001) # test for the population mean
pr = np.zeros(len(mu))
rej = np.zeros(len(mu))
samp = norm.rvs(size = N)
mean_samp = samp.mean()
sd_samp = samp.std(ddof = 1)
for i in range(len(mu)):
    m = mu[i]
    t_crit = (mean_samp-m)/(sd_samp/np.sqrt(N))
    if t_crit>=0:
        p = 2*(1-st.cdf(t_crit, df = N-1))
    else:
        p = 2*st.cdf(t_crit, df = N-1 )
    pr[i] = p
    res = ttest_1samp(samp, popmean = m)
    # t1,t2 tuples for prints
    t1 = t_crit, res[0]
    t2 = p, res[1]
    #print('\n-- t_crit = %.5f \tres[0] = %.5f' % t1)
    #print('\n-- p = %.5f \tres[1] = %.5f' % t2)
    if p<0.05:
        #print('\nmu =',m,' rejected')
        rej[i] = 1
    else:
        #print('\nmu =',m,' not rejected')
        rej[i] = 0
plt.plot(mu,rej,'r')
plt.plot(mu,pr,'b')
plt.plot(mu,len(mu)*[0.05],'g')
plt.title('Means rejected (p-value: blue), (threshold: green)')
plt.xlabel('mean')
plt.ylabel('Reject = 1 (red)')
plt.ylim(-.05,1.05)
plt.show()

Output: