Python course University of Heidelberg Wintersemester 2016/2017

Solutions Day 3 (October 12)

In [39]:
import numpy as np
import matplotlib.pyplot as plt
%matplotlib inline

10.01

In [40]:
np.logspace(-20,-10,11)
Out[40]:
array([  1.00000000e-20,   1.00000000e-19,   1.00000000e-18,
         1.00000000e-17,   1.00000000e-16,   1.00000000e-15,
         1.00000000e-14,   1.00000000e-13,   1.00000000e-12,
         1.00000000e-11,   1.00000000e-10])
In [41]:
np.array(10*[2.])
#
2*np.ones(10)
Out[41]:
array([ 2.,  2.,  2.,  2.,  2.,  2.,  2.,  2.,  2.,  2.])
In [42]:
np.zeros(5, dtype=np.float32)
Out[42]:
array([ 0.,  0.,  0.,  0.,  0.], dtype=float32)

10.02

In [43]:
x=np.random.poisson(100,10)
x[1:] - x[:-1]
Out[43]:
array([ 18,   4, -15,  11,   5, -15,  12,  -9,  14])

10.03

In [44]:
year, temp = np.loadtxt('data/munich_temperatures_average_with_bad_data.txt',
                        unpack=True)
temp_red=temp[(temp>-90) & (temp<90)]
print (len(temp)-len(temp_red),'elements were removed')
60 elements were removed

11.01

In [45]:
year, temp = np.loadtxt('data/munich_temperatures_average_with_bad_data.txt',
                        unpack=True)
keep=(temp>-90) & (temp<90)
In [46]:
plt.plot(year[keep],temp[keep], marker='.',linewidth=0)
Out[46]:
[<matplotlib.lines.Line2D at 0x7fe51d40dd30>]
In [47]:
plt.plot(year[keep]%1,temp[keep], marker='.',linewidth=0)
Out[47]:
[<matplotlib.lines.Line2D at 0x7fe51d448a90>]

11.02

In [48]:
# define normalized Gaussian with mean 'mu' and sigma 'sig'
def gaussian(x,mu,sig):
    return (1/(np.sqrt(2*np.pi)*sig))*np.exp(-(x-mu)**2/(2*sig**2))
In [49]:
#  Gaussian with mean 10 and sigma sqrt(10)
x=np.linspace(-5,30,100)
d=np.random.normal(7,np.sqrt(7),10000)
_=plt.hist(d,bins=np.linspace(-5,30,36))

plt.plot(x,10000*gaussian(x,7,np.sqrt(7)),color='red',linewidth=3)
Out[49]:
[<matplotlib.lines.Line2D at 0x7fe51d3b27f0>]
In [50]:
#  I plot here the sample from the Poisson distribution together with the Gaussian
x=np.linspace(-5,30,100)
d=np.random.poisson(7,10000)
_=plt.hist(d,bins=np.linspace(-5,30,36))

plt.plot(x,10000*gaussian(x,7,np.sqrt(7)),color='red',linewidth=3)
Out[50]:
[<matplotlib.lines.Line2D at 0x7fe51d105d30>]

11.03

In [51]:
x=np.arange(-10,10,0.1)
y=np.arange(-10,10,0.1)

xx,yy   = np.meshgrid(x,y)    # create arrays for the coordinates
r1sq=xx**2+(yy-5)**2          # work out radii
r2sq=xx**2+(yy+5)**2


b1x,b1y   = - (yy-5)/r1sq, xx/r1sq # claculate magnetic field vectors
b2x,b2y   = - (yy+5)/r2sq, xx/r2sq

plt.streamplot(x,y,b1x+b2x,b1y+b2y,color='k')
Out[51]:
<matplotlib.streamplot.StreamplotSet at 0x7fe51d1232e8>

Solution for the coil

In [52]:
a=5                        #radius of the coil
n=90                       #elements on the coil

x=np.arange(-10,10,0.05)
y=np.arange(-10,10,0.05)
dphi=2*np.pi/n

xx,yy=np.meshgrid(x,y)     #generate coordinate grid
bx=0*xx
by=0*yy

for phi in np.arange(0,2*np.pi,dphi):
    cos=np.cos(phi)
                           #separation coil element-observer
    rp=np.sqrt((xx-a*cos)**2+a**2*(1.0-cos**2)+yy**2) 

                           #magnetic field components (cross product)
    bx+=-a*cos*yy*dphi/rp**3       
    by+=-a*(a-cos*xx)*dphi/rp**3

plt.streamplot(x,y,bx,by,color='k')
Out[52]:
<matplotlib.streamplot.StreamplotSet at 0x7fe51cde7630>

Monte Carlo Error propagation

In [53]:
# Defined constant(s)
G = 6.67384e-11  # SI units

# Define values to sample from
mean_m_1 = 40.e4
sigma_m_1 = 0.05e4
mean_m_2 = 30.e4
sigma_m_2 = 0.1e4
mean_r = 3.2
sigma_r = 0.01

Standard error propagation

In [54]:
# Compute mean and error of force
mean_f = G * mean_m_1 * mean_m_2 / mean_r ** 2
sigma_f = mean_f * np.sqrt((sigma_m_1 / mean_m_2) ** 2
                           + (sigma_m_2 / mean_m_2) ** 2
                           + 4. * (sigma_r / mean_r) ** 2)
print(mean_f, sigma_f)
0.7820906249999999 0.00569109398721

Generate random samples for m_1, m_2 and r and calculate the force

In [55]:
N = 1000000
m_1 = np.random.normal(mean_m_1, sigma_m_1, N)
m_2 = np.random.normal(mean_m_2, sigma_m_2, N)
r = np.random.normal(mean_r, sigma_r, N)

# calculate force
F = G * m_1 * m_2 / r ** 2

print(np.mean(F), np.std(F))
0.782113630984 0.00562954545915

Plot the Monte-Carlo histogram using the option normed=True and the Gaussian from the error propagation

In [56]:
# Define range of output values for plotting
xmin = 0.75
xmax = 0.82

# use Gaussian definition from above!

x = np.linspace(xmin, xmax, 1000)
y = gaussian(x, mean_f, sigma_f)

plt.hist(F, bins=50, range=[xmin, xmax], normed=True)
plt.plot(x, y, color='red', lw=3)
plt.xlabel("Force [N]")
plt.ylabel("Relative Probability")
plt.xlim(xmin, xmax)
Out[56]:
(0.75, 0.82)

Repeat this with larger error bars:

In [57]:
# Define values to sample from
mean_m_1 = 40.e4
sigma_m_1 = 2.e4
mean_m_2 = 30.e4
sigma_m_2 = 10.e4
mean_r = 3.2
sigma_r = 1.0

# Define range of output values for plotting
xmin = -1.
xmax = 5.

# Define number of samples
N = 1000000

## STANDARD ERROR PROPAGATION

# Compute mean and error of force
mean_f = G * mean_m_1 * mean_m_2 / mean_r ** 2
sigma_f = mean_f * np.sqrt((sigma_m_1 / mean_m_2) ** 2
                           + (sigma_m_2 / mean_m_2) ** 2
                           + 4. * (sigma_r / mean_r) ** 2)

# Define Gaussian function
x = np.linspace(xmin, xmax, 1000)
y = gaussian(x, mean_f, sigma_f)

## MONTE-CARLO ERROR PROPAGATION

# Sample from initial values
m_1 = np.random.normal(mean_m_1, sigma_m_1, N)
m_2 = np.random.normal(mean_m_2, sigma_m_2, N)
r = np.random.normal(mean_r, sigma_r, N)

# Compute final values
F = G * m_1 * m_2 / r ** 2

## PLOTTING

plt.hist(F, bins=50, range=[xmin, xmax], normed=True)
plt.plot(x, y, color='red', lw=3)
plt.xlabel("Force [N]")
plt.ylabel("Relative Probability")
plt.xlim(xmin, xmax)
Out[57]:
(-1.0, 5.0)