I am working on the file "Corlett_Assign2.ipynb".
The first task is:
Checking the Forcing
To check that the sinusoidal pressure gradient forcing is inducing a reasonable time-dependent signal in the velocity, I'm plotting the nondimensional surface velocity ($u^{\ast}$) against time. It looks correct, as I'm inducing a pressure gradient dependent on $\cos\left(\frac{time}{T_{tidal}}\right)$, and the surface velocity follows the trend of the forcing (being at the free-slip surface condition).
Can you write Python code for it?

# Plot of Surface Velocity
plt.style.use('fivethirtyeight')
plt.plot(Time.T,Q[n-1,:].T)#,linewidth=2,marker='o')
plt.title('Surface Velocity')
plt.ylabel(r'$u^{\ast}$', fontsize=20)
plt.xlabel(r'$Time$', fontsize=20)
#plt.savefig('SurfaceVel.pdf', format='pdf', dpi=1200)


I am working on the file "Corlett_Assign2.ipynb".
The first task is:
Motivation and Discretizing
This problem was motivated as an extension of the probelm I posed in Assignment 1; after solving for the velocity profile forced by a given barotropic tide (parameterized as a fixed surface slope), I proposed modeling the velocity profile under a time-dependent tide (taken to be a sinusoidal M2 tide, with a tidal period of 12.44 hours). In keeping with the earlier problem, I utilize a no-slip bottom boundary condition (taking $u_0$ equal to zero) and a free-slip surface boundary condition (where the flux to the surface is equal to zero).
I begin with the Navier-Stokes equation for $u$:
$$\frac{\partial u}{\partial t} + u \cdot \nabla u = -\frac{1}{\rho}\frac{\partial p}{\partial x} + \frac{\partial}{\partial z}\left[K \frac{\partial u}{\partial z}\right] + F$$
where $u$ is the horizontal velocity, $K$ is an eddy diffusivity, and $\frac{\partial p}{\partial x}$ is the barotropic pressure gradient induced by one phase of the tide, similar to Assigment 1. I can now neglect advection and external forcings (as the forcing for the assignment will be contained within the pressure gradient). In addition, I assume hydrostatic conditions so that $\frac{\partial p}{\partial x} = \rho g \frac{\partial h}{\partial x}$. Our initial equation has now become:
$$\frac{\partial u}{\partial t} = -g\frac{\partial h}{\partial x} + \frac{\partial}{\partial z}\left[K \frac{\partial u}{\partial z}\right]$$
in which $\frac{\partial h}{\partial x}$ is prescribed. As I wish for the barotropic pressure gradient to vary in time (to simulate the M2 tide), I assume that $h = \eta\cos\left(2\pi\frac{time}{T_{tidal}}\right)$, where $T_{tidal}$ is the period of our tide (12.44 hours). Substituting for $h$ and rewriting:
$$\frac{\partial u}{\partial t} + g\cos\left(2\pi\frac{time}{T_{tidal}}\right)\frac{\partial \eta}{\partial x} = \frac{\partial}{\partial z}\left[K \frac{\partial u}{\partial z}\right]$$
Similar to Assignment 1, I am still prescribing the slope, but here it sets a maximum slope amplitude for the...
Can you write Python code for it?

def cranknicolson(T,T_del,Timesteps,n,eta,u0,U,Fr,Re,K):
    '''This iteration scheme moves a Gauss-Seidel estimate forward at a given time interval using a Crank-Nicolson scheme

    INPUTS:
    T = Period of forcing fluctuations
    T_del = timestep
    Timesteps = number of timesteps to move forward
    n = number of depth bins
    eta = amplitude of sinusoidal forcing
    u0 = bottom boundary condition
    U = mean barotropic velocity
    Fr = Froude number of flow
    Re = Reynolds number of flow
    K = diffusivity matrix

    OUTPUT:
    Time = time field
    Depth = depth field (grid center)
    Q = final estimated field over time'''

    #K=ones(n+1)
    #K=array(range(1,n+2))
    #K=array(range(n+2,1,-1))
    K=K/float(max(K)) #Nondimensionalize K

    # Define distances at Face (F) and Center (C) = ensure nondimensionalized
    Z_f=range(-n,0,1);Z_f=[x / float(n) for x in Z_f];Z_f=append(append([-1-(1/float(n))],Z_f),[0]);Z_f=Z_f[0:size(Z_f)-1]+(diff(Z_f))/2.0;
    Z_c=range(-n,0,1);Z_c=[x / float(n) for x in Z_c];Z_c=append(append([-1-(1/float(n))],Z_c),[0]);

    #Begin stepping forward in time
    for time in range(0,Timesteps):
        #Solve for initial state using boundary conditions

        #Construct A matrix - dependent on time iteration scheme
        if time == 0: #Solving for initial conditions
            print(time),
            # Construct 'A' Matrix
            A=zeros((n,n))
            for item in range(1,n+1): #Start from bed and work to surface
                if item>1:
                    A[item-1,item-2]=-(K[item-1]/((Z_f[item]-Z_f[item-1])*(Z_c[item]-Z_c[item-1])) )

                A[item-1,item-1]=+( (K[item-1]/((Z_f[item]-Z_f[item-1])*(Z_c[item]-Z_c[item-1]))) + (K[item]/((Z_f[item]-Z_f[item-1])*(Z_c[item+1]-Z_c[item]))) )
                if item == n: #Sets free-slip boundary condition at the surface
                    A[item-1,item-1]=+( (K[item-1]/((Z_f[item]-Z_f[item-1])*(Z_c[item]-Z_c[item-1]))) )

                if...


I am working on the file "Corlett_Assign2.ipynb".
The first task is:
The plot below illustrates the effects of the linear diffusivity profile; the most grabbing adjustment is the asymmetry of the solution due to the initial condition. I'm not sure why the initial profile is provides an extreme starting point for the time iteration scheme, but plotting over longer periods of time (i.e. a full tidal cycle) reveals that the stable surface velocity maxima are between -1.5 and 1.5 $u^{\ast}$. Focussing on the smaller deviations, you can barely see the effects of the linear diffusivity near -1.8 $z^{\ast}$, in which the grid cells closer to the bathymetry adjust to the forcing at a slightly faster rate than the cells near the surface.
Can you write Python code for it?

#Plot of changes over time
plt.figure()
plt.style.use('fivethirtyeight')
for int in range(0,20):
    lines=plt.plot(-append(append(Q[0,0]*0,Q[:,int*1]),Q[size(Q,0)-1,int*1]),matrix(Depth).T) #Append boundary conditions
    plt.text(-Q[size(Q,0)-1,int*1]-0.05, 0.03, (Time[0,int]*1), fontproperties='serif', fontsize=12)
    #plt.setp(lines, linewidth=2.0)
plt.title('$u$ over Time (hours)')
plt.ylim([Depth.min(),0.1]);#plt.xlim([-5e6,5e6])
plt.ylabel(r'$z^{\ast}$', fontsize=20)
plt.xlabel(r'$u^{\ast}$', fontsize=20)
plt.grid('on')


I am working on the file "Corlett_Assign2.ipynb".
The first task is:
The velocity field over time
Having run the semi-implicit Crank-Nicolson scheme forward in time through one tidal cycle, I checked to ensure that the scheme was producing reasonable velocity profiles.
In the figure below, I've shown the velocity profile changing over one half of the tidal cycle, smoothly switching directions as the forced pressure gradient changes sign. The result appears to be accurate; as the diffusivity is constant throughout the water column, each grid cell adjusts to the barotropic pressure gradient without retaining information from the previous timestep. In essence, the forward steps through time in this case could have been modelled independently and joined into a single matrix after the calculations.
Can you write Python code for it?

#Plot of changes over time
plt.figure()
plt.style.use('fivethirtyeight')
for int in range(0,16):
    #lines=plt.plot(append(Q[:,int],Q[19,int]),(matrix([range(0,20)]).T/20.0))
    lines=plt.plot(-append(append(Q[0,0]*0,Q[:,int*1]),Q[size(Q,0)-1,int*1]),matrix(Depth).T) #Append boundary conditions
    plt.text(-Q[size(Q,0)-1,int*1]-0.025, 0.03, (Time[0,int]*1), fontproperties='serif', fontsize=12)
    #plt.setp(lines, linewidth=2.0)
plt.title('$u$ over Time (hours)')
plt.ylim([Depth.min(),0.1]);#plt.xlim([-5e6,5e6])
plt.ylabel(r'$z^{\ast}$', fontsize=20)
plt.xlabel(r'$u^{\ast}$', fontsize=20)
plt.grid('on')
#plt.legend(['0','20','40','60','80','100','120'])
#plt.xscale('log')
plt.show()


I am working on the file "Corlett_Assign2.ipynb".
The first task is:
Variations on the Problem - Linear Diffusivity
To vary the conditions going into the problem, I first decided to adjust the diffusivity field to more accurately portray a decrease in mixing as you move down through the water column. The figure immediately below reflects the new linear diffusivity profile.
Can you write Python code for it?

# Create K matrix
K=ones(n+1)*(10**-2)
new=list(arange(1,n+1))
for l in new:
    K[l]=(K[l]*float(l)) #New varying diffusivity, with higher values closer to the surface

# Plot diffusivity profile
plt.plot(append(K,K[n]),Depth)
plt.title('Linear Diffusivity Profile')
plt.ylim([Depth.min(),0.1])
plt.ylabel(r'$z^{\ast}$', fontsize=20)
plt.xlabel(r'$K$', fontsize=20)
plt.show()

## Re-Run the Crank-Nicolson scheme, having initialized the fields
[Time,Depth,Q]=cranknicolson(12.44,0.5,40,n,eta,u0,U,Fr,Re,K)


I am working on the file "Corlett_Assign3.ipynb".
The first task is:
1. Sensitivity of the System to Boundary Conditions
Note that the spectral radius changes as the boundary conditions change, but not when the values change. The spectral radius is not influenced by boundary condition values per say, but it is influenced by the type of boundary conditions present within the system. This is because the values are not introduced to the matrices $[B]$ or $[C]$, but the boundary conditions will influence the values on the diagonals of the matrix $[A]$, which will either end up in matrices $[B]$ or $[C]$ depending on the iteration scheme.
See below for comparison values:
Can you write Python code for it?

#Initialize a comparison
n=20 #n must be greater than 6 for my SOR code to work - the issue lies with calculating eigenvalues.
K=0.3
v=0.5
u0=0.
u1=1.

#[A,b]=dirichlet(n,v,u0,u1,matrix(arange(0,n+2)).T,matrix(arange(0,n+2)).T,K*ones([n+1,1]))
#[A,b]=neumann_stable(n,v,u1,matrix(arange(0,n+2)).T,matrix(arange(0,n+2)).T,K*ones([n+1,1]))


I am working on the file "Corlett_Assign3.ipynb".
The first task is:
2. Sensitivity of the solution to $\nu$
The convergence of the system is sensitive to the value of $\nu$, as $\nu$ will change the values on the diagonal of the matrix $[A]$, changing the determinate of $[B]$ in the process of calculating its inverse, and thus the spectral radius ($\rho$).
Can you write Python code for it?

[A,b]=dirichlet(n,0.5,1,0,matrix(arange(0,n+2)).T,matrix(arange(0,n+2)).T,K*ones([n+1,1]))
[Q,I,S]=space_iterate('jacobi',A,b,1)
[Q,I,S]=space_iterate('gaussseidel',A,b,1)
[Q,I,S]=space_iterate('sor',A,b,1)

nu=[1.0e3,1.0e2,1.0e1,9.0,8.0,7.0,6.0,5.0,4.0,3.0,2.0,1.0e0,.9,.8,.7,.6,.5,.4,.3,.2,1.0e-1,1.0e-2,1.0e-3]

#fig, axs = plt.subplots(1,2)
#,ax=axs[1]
plt.figure(figsize=(20,5))
plt.subplot(121)
for R in range(0,size(nu)): #Varies the value of nu
    [A,b]=dirichlet(n,nu[R],1,0,matrix(arange(0,n+2)).T,matrix(arange(0,n+2)).T,K*ones([n+1,1]))

    [Q,Is,Ss]=space_iterate('sor',A,b,1)
    [Q,Ig,Sg]=space_iterate('gaussseidel',A,b,1)
    [Q,Ij,Sj]=space_iterate('jacobi',A,b,1)

    plt.semilogx(nu[R],Ss,'ok')
    plt.semilogx(nu[R],Sg,'sk')
    plt.semilogx(nu[R],Sj,'+k')

    if int == 1.0:
        plt.legend(['SOR','Gauss-Seidel','Jacobi'])
        #plt.title('Surface Velocity')
        plt.ylabel(r'$\rho$', fontsize=20)
        plt.xlabel(r'$\nu$', fontsize=20)

plt.subplot(122)
for R in range(0,size(nu)): #Varies the value of nu
    [A,b]=dirichlet(n,nu[R],1,0,matrix(arange(0,n+2)).T,matrix(arange(0,n+2)).T,K*ones([n+1,1]))

    [Q,Is,Ss]=space_iterate('sor',A,b,1)
    [Q,Ig,Sg]=space_iterate('gaussseidel',A,b,1)
    [Q,Ij,Sj]=space_iterate('jacobi',A,b,1)

    plt.semilogx(nu[R],Is,'ok')
    plt.semilogx(nu[R],Ig,'sk')
    plt.semilogx(nu[R],Ij,'+k')

    if R == 1.0:
        plt.legend(['SOR','Gauss-Seidel','Jacobi'])
        #plt.title('Surface Velocity')
        plt.ylabel(r'$Iterations$', fontsize=20)
        plt.xlabel(r'$\nu$', fontsize=20)


I am working on the file "Corlett_Assign3.ipynb".
The first task is:
Here I create the code that will perform a specified iteration scheme, with the option of specifying a value for $\omega$.
Can you write Python code for it?

def space_iterate(method,A,b,resid,**optional):
    '''Uses sparse matrices'''

    if ('w' in optional):
        #print 'w found, it is ', optional['w']
        w = optional['w']
    else:
        #print 'no w found, assumed to be 1.17 if needed.'
        w = 1.17
        #w = 1.02

    n = max(A.get_shape())
    t = 0;
    Q = b[:,0]
    Rold = 100 #initialize value
    Rnew = 1
    while (absolute(Rnew - Rold)/float((absolute([Rold]))))*100.0 > resid:
        t = t+1
        Rold = Rnew
        Q = append(Q,Q[:,0].dot(0.),axis=1)

        if method == 'jacobi': #Jacobi iteration scheme

            B = sparse.tril(A,0) - sparse.tril(A,-1) #only the diagonal
            C = sparse.triu(A,1) + sparse.tril(A,-1) #only off-diagonal

            Q[:,t] = linal.inv(B).dot(b - C.dot(Q[:,t-1]))

        elif method == 'gaussseidel': #Gauss-Seidel iteration scheme

            B = sparse.tril(A,0)
            C = sparse.triu(A,1)

            Q[:,t] = linal.inv(B).dot(b - C.dot(Q[:,t-1]))

        elif method == 'sor': #SOR method
            #Q[i,t] = w*Q[i,t] + (1-w)*Q[i,t-1]

            B = sparse.tril(A,-1)*(float(w)) + (sparse.tril(A,0)-sparse.tril(A,-1))
            C = ( (sparse.tril(A,0)-sparse.tril(A,-1)).dot(float(w-1))) + (sparse.triu(A,1).dot(float(w)) )

            #B = - sparse.tril(A,-1)*(float(w)) + (sparse.tril(A,0)-sparse.tril(A,-1))
            #C = ( (sparse.tril(A,0)-sparse.tril(A,-1)).dot(float(1-w))) + (sparse.triu(A,1).dot(float(w)) )

            Q[:,t] = linal.inv(B).dot((float(w)*b) - C.dot(Q[:,t-1]))

        else:
            print('Improper Option - program closing.')
            return

        Rnew = mean(Q[:,t])
        #print (absolute(Rnew - Rold)/float((absolute(Rold))))*100.0

    B = B.tocsc() #convert sparse matrices to csc format
    C = C.tocsc()

    print('Iterations = '+str(t)+'; Spectral Radius =...


I am working on the file "Corlett_Assign3.ipynb".
The first task is:
The following code will initialize the $[A]$ and $[b]$ matrices according to the inputs, and depending on which code I call, as they use Neumann + Dirichlet and Dirichlet-only boundary conditions, respectively.
Can you write Python code for it?

def neumann_stable(n,v,u0,Z_f,Z_c,K):
    #Create Neumann + Dirichlet boundary conditions, yielding matrices A + b
    A=zeros((3,n)) # For solving for 'n+1' solution
    for item in range(1,n+1): #Start from bed and work to surface
        #j-1
        if item>1:
            A[0,item-2]=+(K[item-1]/((Z_f[item]-Z_f[item-1])*(Z_c[item]-Z_c[item-1])) )
        #j
        A[1,item-1]=-( (K[item-1]/((Z_f[item]-Z_f[item-1])*(Z_c[item]-Z_c[item-1]))) + (K[item]/((Z_f[item]-Z_f[item-1])*(Z_c[item+1]-Z_c[item]))) + v)
        if item == n: #Sets free-slip boundary condition at the surface
            A[1,item-1]=-( (K[item-1]/((Z_f[item]-Z_f[item-1])*(Z_c[item]-Z_c[item-1]))) + v)
        #j+1
        if item != n:
            A[2,item]=+(K[item]/((Z_f[item]-Z_f[item-1])*(Z_c[item+1]-Z_c[item])) )

    A = sparse.spdiags(A,array([-1,0,1]),n,n)

    # Construct Boundary Condition Matrix
    b=zeros(size(A,1))
    b[0]=b[0] + (u0* (K[item-1]/((Z_f[item]-Z_f[item-1])*(Z_c[item]-Z_c[item-1]))) ) #Because u0 is zero, this line does nothing.

    # Define + Apply guess + boundary conditions
    b=matrix(b).T
    return[A,b]

def dirichlet(n,v,u0,u1,Z_f,Z_c,K):
    #Create Dirichlet boundary conditions, yielding matrices A + b
    A=zeros((3,n)) # For solving for 'n+1' solution
    for item in range(1,n+1): #Start from bed and work to surface
        #j-1
        if item>1:
            A[0,item-2]=+(K[item-1]/((Z_f[item]-Z_f[item-1])*(Z_c[item]-Z_c[item-1])) )
        #j
        A[1,item-1]=-( (K[item-1]/((Z_f[item]-Z_f[item-1])*(Z_c[item]-Z_c[item-1]))) + (K[item]/((Z_f[item]-Z_f[item-1])*(Z_c[item+1]-Z_c[item]))) + v )
        #j+1
        if item != n:
            A[2,item]=+(K[item]/((Z_f[item]-Z_f[item-1])*(Z_c[item+1]-Z_c[item])) )

    A = sparse.spdiags(A,array([-1,0,1]),n,n)

    # Construct Boundary Condition Matrix
    b=zeros(size(A,1))
    b[0]=b[0] + (u0* (K[1-1]/((Z_f[1]-Z_f[1-1])*(Z_c[1]-Z_c[1-1]))) )
    b[n-1]=b[n-1] + (u1* (K[n-1]/((Z_f[n]-Z_f[n-1])*(Z_c[n]-Z_c[n-1]))) )

    # Define +...


I am working on the file "Corlett_Assign5.ipynb".
The first task is:
1.2 - 1$^{st}$order in time and 4$^{th}$order in space
In this example, I've used the explicit Forward Euler scheme in time, and a fourth order centered-difference scheme in space. The discretization of equation (1) in this case takes the following form:
\begin{equation}
    \theta^{t+1}{x} = \theta^{t}{x} - \frac{\lambda}{12} \left[\theta^{t}{x-2} - 8\theta^{t}{x-1} + 8\theta^{t}{x+1} - \theta^{t}{x+2} \right]
\end{equation}
However, the fourth-order scheme requires two points spatially behind the point to be solved; in order to work around this limitation, I have applied the same first-order spatial scheme used above to the boundary cells and a second-order spatial scheme to the next immediate cell to provide a buffer for the interior iterative process.
Can you write Python code for it?

c=1.
t_del = 0.1
x_del = 0.1
n=100;
t_steps=100

T=matrix(zeros((n+1,1)))
for t in range(3,23):
    T[t,0]=sin(((t-3)/19.)*2*pi)

Y=(c*t_del)/x_del
Y=0.7 #Force value to be less than one to illustrate dissipation
for Tint in range(0,t_steps):
    T=append(T,matrix(zeros((shape(T)[0],1))),axis=1)
    for int in range(0,shape(T)[0]-1):
            if int==0 or int==shape(T)[0]-2:
                T[int+1,Tint+1]=T[int+1,Tint]-Y*((T[int+1,Tint]-T[int,Tint]))
            elif int==1 or int==shape(T)[0]-3:
                T[int+1,Tint+1]=T[int+1,Tint]-Y*((T[int+1,Tint]-T[int-1,Tint])/2)
            else:
                T[int+1,Tint+1]=T[int+1,Tint]-Y*((T[int-2,Tint]-8*T[int-1,Tint]+8*T[int+1,Tint]-T[int+2,Tint])/(12))

plt.figure(figsize=(12,5))
plt.subplot(121)
plt.plot(arange(0,n+1)*x_del,array(T),linewidth=0.5);plt.title('Propagation of a Sine wave')
plt.ylabel('$\eta$');plt.xlabel('x')
plt.subplot(122)
plt.contourf(arange(0,n+1)*x_del,arange(0,t_steps+1)*t_del,array(T).T,cmap=cm.RdBu_r)
plt.colorbar();plt.title('Signal over Time');plt.xlabel('x');plt.ylabel('Time')
plt.show()


I am working on the file "Corlett_Assign5.ipynb".
The first task is:
1.3 - 2$^{nd}$order in time and 4$^{th}$order in space
In this scenario, I have increased the accuracy of the above scheme only in time, using a second-order Leap-Frog method, while retaining the fourth-order centered-difference scheme in space. Thus, the discrete form of equation (1) has become:
\begin{equation}
    \theta^{t+1}{x} = \theta^{t-1}{x} - \frac{2\lambda}{12} \left[\theta^{t}{x-2} - 8\theta^{t}{x-1} + 8\theta^{t}{x+1} - \theta^{t}{x+2} \right]
\end{equation}
Can you write Python code for it?

c=1.
t_del = 0.1
x_del = 0.1
n=100;
t_steps=600

T=matrix(zeros((n+1,1)))
for t in range(3,23):
    T[t,0]=sin(((t-3)/19.)*2*pi)

Y=(c*t_del)/x_del
Y=0.01 #Force value to be less than one to illustrate dissipation
for Tint in range(0,t_steps):
    T=append(T,matrix(zeros((shape(T)[0],1))),axis=1)
    for int in range(0,shape(T)[0]-1):
        if Tint==0:
            T[int+1,Tint+1]=T[int+1,Tint]-Y*((T[int+1,Tint]-T[int,Tint]))
        else:
            if int==0 or int==shape(T)[0]-2:
                T[int+1,Tint+1]=T[int+1,Tint-1]-2*Y*((T[int+1,Tint]-T[int,Tint]))
            elif int==1 or int==shape(T)[0]-3:
                T[int+1,Tint+1]=T[int+1,Tint-1]-2*Y*((T[int+1,Tint]-T[int-1,Tint])/2)
            else:
                T[int+1,Tint+1]=T[int+1,Tint-1]-2*Y*((T[int-2,Tint]-8*T[int-1,Tint]+8*T[int+1,Tint]-T[int+2,Tint])/(12))

plt.figure(figsize=(12,5))
plt.subplot(121)
plt.plot(arange(0,n+1)*x_del,array(T),linewidth=0.05);plt.title('Propagation of a Sine wave')
plt.ylabel('$\eta$');plt.xlabel('x')
plt.subplot(122)
plt.contourf(arange(0,n+1)*x_del,arange(0,t_steps+1)*t_del,array(T).T,cmap=cm.RdBu_r)
plt.colorbar();plt.title('Signal over Time');plt.xlabel('x');plt.ylabel('Time')
plt.show()


I am working on the file "Corlett_Assign5.ipynb".
The first task is:
By incrementally changing the accuracy (and thus order) of the schemes, it is apparent that the order of the time iteration scheme is much more important at driving dispersion and instabilities of the original signal. Increasing the spatial order serves to increase the dissipation of the signal, quickly spreading and muting the disturbance.
1.4 - Evaluation of Amplification + Dispersion Relation
Amplitude error is evaluated from an entire scheme, while the dispersion (or phase error) is evaluated only from the spatial differencing scheme.
Numerical Dissipation
For a Forward Euler method:
\begin{gather}
    \frac{\theta^{n+1} - \theta^{n}}{\Delta t} + c \left[ \frac{\theta^{n}{i} - \theta^{n}{i-1}}{\Delta x} \right] = 0 ~\text{for c > 0} \
    \text{Take }\theta^{n} = \hat{\theta}^{n}e^{ikx} ~\text{assuming a wave form} \
    \hat{\theta}^{n+1} = \hat{\theta}^{n} - \hat{\theta}^{n}c\frac{\Delta t}{\Delta x} \left[ e^{ikx} - e^{ik(x+\Delta x)} \right] \
    \hat{\theta}^{n+1} = \hat{\theta}^{n} \left[ 1 - \lambda \left( 1 - e^{ik\Delta x} \right) \right] ~\text{where }\lambda = c\frac{\Delta t}{\Delta x} \
    \frac{\hat{\theta}^{n+1}}{\hat{\theta}^{n}} = \left[ 1 - \lambda \left( 1 - \cos(k\Delta x) - i\sin(k\Delta x) \right) \right] \
    \left[ \frac{\hat{\theta}^{n+1}}{\hat{\theta}^{n}} \right]^{2} = \left[ 1 - \lambda \left( 1 - \cos(k\Delta x) \right) \right]^{2} + \lambda^{2}\sin^{2}(k\Delta x) \
    \text{Taking } k\Delta x = \frac{\pi}{2}: \
    \left[ \frac{\hat{\theta}^{n+1}}{\hat{\theta}^{n}} \right]^{2} = \left[ 1 - \lambda \right]^{2} + \lambda^{2} \
    \text{Therefore, for }\left[ \frac{\hat{\theta}^{n+1}}{\hat{\theta}^{n}} \right] \leq 1, \lambda = c\frac{\Delta t}{\Delta x} \leq 1
\end{gather}
Thus, we reach the CFL condition, required such that no waves outrun the explicit time-stepping method. Numerical dissipation occurs when $\lambda$ is less than one, as it effectively describes the change in amplitude of the signal from one time step to the next. Following a similar procedure for the...
Can you write Python code for it?

dx=1
c = 1.
k=arange(0,pi+0.1,pi/100.)

plt.figure(figsize=(6,6))
plt.plot(k,c*k)
plt.plot(k,(c/dx)*sin(k*dx))
plt.plot(k,(c/(6*dx))*(8*sin(k*dx) - sin(2*k*dx)))
plt.legend(['$\omega = ck$','1$^{st}$ Order Upwind Scheme','4$^{th}$ Order Centered-Difference'])
plt.xticks(arange(0,1.1,1/10.)*pi,['0','0.1$\pi$', '0.2$\pi$', '0.3$\pi$','0.4$\pi$','0.5$\pi$','0.6$\pi$','0.7$\pi$','0.8$\pi$','0.9$\pi$','$\pi$']);
plt.xlim((0,1*pi));plt.ylim((0,1*pi))
plt.ylabel('$\omega$ - Frequency');plt.xlabel('$k$ - Wave Number');plt.title('Numerical Dispersion Relation');
plt.show()

##Attempt to find points where C=C_g for each of the methods; did not look nice.
#k = pi/2.
#dx = arange(0,100+(1/50.),1/50.)+(1/50.)
#plt.figure(figsize=(6,6))
#plt.plot(dx,abs(((c/(dx*k))*(sin(k*dx)))/((c/(k))*(cos(k*dx)))))
#plt.plot(dx,abs(((c/(6*dx*k))*(8*sin(k*dx) - sin(2*k*dx)))/((c/(3*dx*k))*(4*cos(k*dx) - cos(2*k*dx)))))
#plt.legend(['1$^{st}$ Order Upwind','4$^{th}$ Order Centered']);plt.xlim((0,10));plt.ylim((0,10));
#plt.xlabel('$\delta x$');plt.ylabel('C/C$_{g}$')
#plt.show()


I am working on the file "Corlett_Assign5.ipynb".
The first task is:
The above streamfunction, and corresponding velocity fields are now used to advect our tracer through the grid, following the specifications described above.
Can you write Python code for it?

#Application of Advection scheme: Finite Volume + Flux form of equations

upos=[]; uneg=[];
vpos=[]; vneg=[];

T_old=zeros(shape(T))
T_new=zeros(shape(T))
T_old[:]=T[:]

#Begin time-stepping
for t in range(0,t_steps):

    upos[:] = 0.5*(u[:]+abs(u[:])); upos = array(upos)
    vpos[:] = 0.5*(v[:]+abs(v[:])); vpos = array(vpos)
    uneg[:] = 0.5*(u[:]-abs(u[:])); uneg = array(uneg)
    vneg[:] = 0.5*(v[:]-abs(v[:])); vneg = array(vneg)

    Dx=zeros((n+1,m+1))
    for i in range(0,n-1):
        Dx[i,:]=(T[i+1,:]-T[i,:])
    Dx[n,:]=(T[0,:]-T[n,:]) #Provide cyclical boundary conditions

    Dy=zeros((n+1,m+1))
    for i in range(0,m-1):
        Dy[:,i]=(T[:,i+1]-T[:,i])
    Dy[:,m]=(T[:,0]-T[:,m]) #Provide cyclical boundary conditions

    #Calculate Fluxes (using QUICK)
    fx=zeros((n+1,m+1))
    for i in range(0,n):
        if i==0 or i==n-1:
            fx[i,:] = 0.5*(T[i,:]+ T[i+1,:])* u[i,:]
        else:
            fx[i,:] = u[i,:]*0.5*(T[i+1,:]+T[i,:]) -0.125*upos[i,:]*(Dx[i,:]- Dx[i-1,:]) -0.125*uneg[i,:]*(Dx[i+1,:]-Dx[i,:]); #3rd Order
    fy=zeros((n+1,m+1))
    for i in range(0,m):
        if i==0 or i==m-1:
            fy[:,i] = 0.5*(T[:,i]+ T[:,i+1])* v[:,i]
        else:
            fy[:,i] = v[:,i]*0.5*(T[:,i+1]+T[:,i]) -0.125*vpos[:,i]*(Dy[:,i]- Dy[:,i-1]) -0.125*vneg[:,i]*(Dy[:,i+1]-Dy[:,i]); #3rd Order

    #Adjust to be a leapfrog scheme after the first timestep
    if t==0:
        C=1
    else: C=1

    for i in range(1,n):
        for j in range(1,m):
            T_new[i,j] = T[i,j] - C*dt*(-fx[i-1,j]+fx[i,j]-fy[i,j-1]+fy[i,j])

    #Boundary
    T_new[n,:]=T_new[n-1,:]
    T_new[0,:]=T_new[1,:]
    T_new[:,m]=T_new[:,m-1]
    T_new[:,0]=T_new[:,1]

    T_old[:]=T[:]
    T[:]=T_new[:]

    if t%100 == 0:
        plt.figure(figsize=(10,4))
        plt.subplot(121);plt.pcolor(x,y,T.T,cmap=cm.RdBu_r)
        plt.clim([-1.2,1.2]);plt.plot(x,ones(shape(x))*(50*dy),linewidth=0.5,color='k')
        plt.colorbar();plt.title('Tracer Distribution at time...


I am working on the file "Correct Coordinates & Sea Lion Counts.ipynb".
The first task is:
Due to the fact some images are mismatched in the training set, and will not work for this method (reference to datacanary's post), I removed those images from the entire list of training files.
Can you write Python code for it?


I am working on the file "Correct Coordinates & Sea Lion Counts.ipynb".
The first task is:
Generating an Error Report
Here I compared the number of sea lions counted by Radu's method, to the "true" counts given in train.csv. The function below takes in the count file (initial_count.csv) and compares it to train.csv. It then prints a list of images along with the specific categories of sea lions and the predicted values by Radu's method, versus the "true" values from train.csv
Can you write Python code for it?

def report_error(count_file):
    # checking that the generated "initial_count.csv" matches "train.csv" true sea lion numbers
    count_df = pd.read_csv(OUT_PATH + count_file, index_col=0)
    true_count_df = pd.read_csv(TRAIN_PATH + 'train.csv')
    categories = ["adult_males", "subadult_males", "adult_females", "juveniles", "pups"]

    wrong_files_dict = {}
    for filename, row in count_df.iterrows():
        train_id = int(filename.partition('.')[0])

        wrong_list = []
        for category in categories:
            predicted_val = int(row[category])
            true_val = int(true_count_df[category][train_id])
            if predicted_val != true_val:
                wrong_list.append([category, predicted_val, true_val])
        if len(wrong_list) != 0:
            wrong_files_dict[int(filename.partition('.')[0])] = wrong_list

    wrong_files_list = list(wrong_files_dict.keys())
    wrong_files_list = sorted(wrong_files_list, key=int)

    for img_id in wrong_files_list:
        filename = str(img_id) + '.jpg'
        wrong_categories = wrong_files_dict[img_id]
        print(filename)
        for item in wrong_categories:
            category = item[0]
            predicted_val = item[1]
            true_val = item[2]
            print('      ' + category + ': predicted=' + str(predicted_val) + ', True=' + str(true_val))

report_error('initial_count.csv')


I am working on the file "Correct Coordinates & Sea Lion Counts.ipynb".
The first task is:
I noticed that there were many images with discrepancies between our generated counts and the train.csv counts. The only way to verify whether or not the generated counts were correct or the train.csv were correct, was to manually check the coordinates for the images with discrepencies.
Note: Images without discrepancies between generated and train.csv counts will not be manually checked, and will be assumed to have accurate coordinates and counts. Other images may be manually checked later, check the bottom for "Edits" to the data files
In order to check the validity of the coordinates, they must be visualized on the image.
Visualizing Coordinates
Radu's Method was implemented here to visualize the extracted coordinates on the dotted training images
Using the function defined below (graph_coord_circles), all we need to do is give it a list of file names, and the name of the coordinates file generated before (initial_coordinates.csv) and the function will draw circles around the coordinates of every file, and save a new jpg file to the output folder with those circles on the image. This will allow us to check if the coordinates are centered correctly on the sea lions.
Can you write Python code for it?

def graph_coord_circles(FILE_NAMES, coord_file):
    coordinates_df = pd.read_csv(OUT_PATH + coord_file)

    for filename in FILE_NAMES:
        new_df = coordinates_df.loc[coordinates_df['filename'] == filename]
        dotted_img = cv2.imread(DOTTED_PATH + filename)

        for index, row in new_df.iterrows():
            if row['category'] == 'adult_males':
                cv2.circle(dotted_img, (int(row['x_coord']), int(row['y_coord'])), 8, (0,0,255), 2)
            elif row['category'] == 'subadult_males':
                cv2.circle(dotted_img, (int(row['x_coord']), int(row['y_coord'])), 8, (250,10,250), 2)
            elif row['category'] == 'pups':
                cv2.circle(dotted_img, (int(row['x_coord']), int(row['y_coord'])), 8, (20,180,35), 2)
            elif row['category'] == 'juveniles':
                cv2.circle(dotted_img, (int(row['x_coord']), int(row['y_coord'])), 8, (180,60,30), 2)
            elif row['category'] == 'adult_females':
                cv2.circle(dotted_img, (int(row['x_coord']), int(row['y_coord'])), 8, (0,42,84), 2)

        cv2.imwrite(OUT_PATH + str(filename.partition('.')[0]) + '_marked.jpg', dotted_img)

# uncomment the line below and run this cell to generate marked images for all the training files
# graph_coord_circles(FILE_NAMES, 'initial_coordinates.csv')


I am working on the file "Correct Coordinates & Sea Lion Counts.ipynb".
The first task is:
Manually Checking Images
Using the images with circles on the coordinates, I checked the images with discrepencies for a couple things:
1. Each circle is centered on a sea lion, not off in the sea (ensuring that the coordinates are on target)
2. Each sea lion has a circle on them (ensuring that every sea lion has coordinates that point towards it, and no sea lion is unmarked)
3. The color of the circle, which indicates category of sea lion, matches the appearance of the sea lion (ensures that the sea lions are labeled with not just the correct coordinates but the correct category)
Based on the conditions above, the data (coordinates and counts) for a specific image may be incorrect. The correct data is assumed to be the initial_coordinates.csv, and I modify the coordinates in initial_coordinates.csv by adding coordinates for missing sea lions and removing coordinates for non-sea lions.
Can you write Python code for it?

# first load in the data from initial_coordinates.csv
correct_coordinates_df = pd.read_csv(OUT_PATH + 'initial_coordinates.csv', index_col=0)


I am working on the file "CorrectingForAssumptions.ipynb".
The first task is:
As shown above, the error from the model is not normally distributed. The error is skewed to the right, similar to the raw data itself.
Additionally, the distribution of error terms is not consistent, it is heteroscadastic.
Inspect the Data and Transform
The data is skewed to the right. The data is transformed by taking its square root to see if we can obtain a more normal distribution.
Can you write Python code for it?

plt.hist(actual)
plt.show()

sqrt_actual = np.sqrt(actual)

plt.hist(sqrt_actual)
plt.show()


I am working on the file "Cosine tuning curves.ipynb".
The first task is:
Plot the results, showing the first 20 neurons only
Can you write Python code for it?

%matplotlib inline
import pylab

pylab.plot(theta_degrees, activity[:,:20])
pylab.xlabel('represented angle')
pylab.ylabel('firing rate (Hz)')
pylab.show()


I am working on the file "Coulomb Matrix.ipynb".
The first task is:
Atoms
Atoms are defined as a list of strings here.
Can you write Python code for it?


I am working on the file "Coulomb Matrix.ipynb".
The first task is:
Generate some random coordinates
Making some random $x,y,z$ coordinates up
Can you write Python code for it?

Coordinates = []
for AtomNumber in range(len(Atoms)):
    Coordinates.append(np.random.rand(3))


I am working on the file "Coulomb Matrix.ipynb".
The first task is:
Molecule
Here we've defined a molecule as a dictionary of atom objects.
We'll loop over the number of atoms, and initialise each dictionary key with an atom.
In an actual run, we'll need to parse information from an xyz file somehow instead.
Can you write Python code for it?

Molecule = dict()

for Index, Atom in enumerate(Atoms):
    Molecule[Index] = __Atom__(Atom, Coordinates[Index])


I am working on the file "Counting Word Frequencies.ipynb".
The first task is:
Although we can display the contents of a directory by using the listdir function, Python needs those names stored in a list in order to iterate over it. We also want to specify that only files with the extension .txt are included. Here we create another function called list_textfiles.
Can you write Python code for it?

def list_textfiles(directory):
    "Return a list of filenames ending in '.txt'"
    textfiles = []
    for filename in listdir(directory):
        if filename.endswith(".txt"):
            textfiles.append(directory + "/" + filename)
    return textfiles


I am working on the file "Counting Word Frequencies.ipynb".
The first task is:
And finally, we'll write a function to tie the two functions together.
Can you write Python code for it?

def get_filename(filepath):
    "Removes the path and file extension from the file name"
    filename = remove_ext(filepath)
    name = remove_dir(filename)
    return name

filenames = []
for files in list_textfiles('data'):
    files = get_filename(files)
    filenames.append(files)


I am working on the file "Counting Word Frequencies.ipynb".
The first task is:
Here is a more extreme example to illustrate the point.
Can you write Python code for it?

print "Instances of the word \'pRiVaCy\':",(count_in_list("pRiVaCy", words))


I am working on the file "Counting Word Frequencies.ipynb".
The first task is:
How about ethics?
Can you write Python code for it?

for words, names in zip(corpus, filenames):
    print"Instances of the word \'ethics\' in",names, ":", count_in_list("ethics", words)


I am working on the file "Counting Word Frequencies.ipynb".
The first task is:
Let's create a function to make the names of the files more readable. First we'll have to strip the the file extension <code>.txt</code>.
Can you write Python code for it?

from os.path import splitext

def remove_ext(filename):
    "Removes the file extension, such as .txt"
    name, extension = splitext(filename)
    return name

for files in list_textfiles('data'):
    remove_ext(files)


I am working on the file "Counting Word Frequencies.ipynb".
The first task is:
Now let's make a function to remove the data/.
Can you write Python code for it?

from os.path import basename

def remove_dir(filepath):
    "Removes the path from the file name"
    name = basename(filepath)
    return name
for files in list_textfiles('data'):
    remove_dir(files)


I am working on the file "Counting Word Frequencies.ipynb".
The first task is:
Now we can call the function for any word we choose. The next example shows that there are 392 occurences of the word privacy contained in the transcripts for the 39th sitting of Parliament.
Can you write Python code for it?

# 6. here the function counts the instances of the word 'privacy'
print "Instances of the word \'privacy\':", (count_in_list("privacy", words))


I am working on the file "Counting Word Frequencies.ipynb".
The first task is:
Now we can display a readable list of the files within our directory.
Can you write Python code for it?

print"There are", len(corpus), "files in the list, named:", ', '.join(filenames),"."


I am working on the file "Counting Word Frequencies.ipynb".
The first task is:
Now, when we count the instances of privacy, we are presented with a total of 846 instances.
Can you write Python code for it?

print "Instances of the word \'privacy\':", (count_in_list("privacy", words))


I am working on the file "Counting Word Frequencies.ipynb".
The first task is:
Part 2: Determining Word Frequencies for the Entire Corpus
Now let's see how this compares to the rest of the corpus. To accomplish this, we must write another function that will read all of the text files in our file folder.

First we need to introduce a function of Python that we've yet to see: modules. Modules are packages of functions and code that serve specific purposes. These are much like functions, but more complex.

The next piece of code imports a module called os, specifically the function listdir. We will use listdir to print a list of all the files in a specific directory. Each of the listed files corresponds to a textual transcript of Hansard. The first nine files refer to the complete transcript for each year from 2006 to 2014, while the last three files are the transcripts corresponding to each sitting of Parliament, in this case the 39th through to the end of the second sitting of the 41st Parliament.
Can you write Python code for it?

# imports the os module
from os import listdir
# calls the listdir function to list the files in a specific directory
listdir("data")


I am working on the file "Counting Word Frequencies.ipynb".
The first task is:
Rather than writing code to open each file individually, we can create another custom function to open the file we pass to it. We'll call this one read_file.
Can you write Python code for it?

def read_file(filename):
    "Read the contents of FILENAME and return as a string."
    infile = open(filename)
    contents = infile.read()
    infile.close()
    return contents


I am working on the file "Counting Word Frequencies.ipynb".
The first task is:
The next step involves iterating through both lists: corpus and filenames, in order to generate a word frequency for each file in the corpus. For this we will use Python's zip function.
Can you write Python code for it?

for words, names in zip(corpus, filenames):
    print"Instances of the word \'privacy\' in",names, ":", count_in_list("privacy", words)


I am working on the file "Counting Word Frequencies.ipynb".
The first task is:
The second problem is that of punctuation. Much like words are case-sensitive, they are also punctuation-sensitive. If a piece of punctuation has been included in the string, it will be included in the search. Here we count the occurrences of privacy, shown here with a comma after the word.
Can you write Python code for it?

print "Instances of the word \'privacy,\':", (count_in_list("privacy,", words))


I am working on the file "Counting Word Frequencies.ipynb".
The first task is:
Unfortunately, there are two distinct problems here, centred around the fact that our function is only counting the string privacy exactly as it appears.

The first problem is that text strings are case-sensitive. If the word contains UPPERCASE and lowercase letters, the word that is searched for will only be counted if the cases match exactly. The following example counts the number of instances of Privacy with the first letter capitalized.
Can you write Python code for it?

print "Instances of the word \'Privacy\':", (count_in_list("Privacy", words))


I am working on the file "Counting Word Frequencies.ipynb".
The first task is:
We could comb through the text to find all of the different instantiations of privacy, and then run the code for each one and add together all of the numbers, but that would be time consuming and potentially inaccurate. Instead, we must process the text further to make the text uniform. In this case we want to make all of the characters lowercase, and remove all of the punctuation.

Python has a function that will do this for us.

We will reload the text file, split the text into distinct words or tokens and then use the the text cleaning function.
Can you write Python code for it?

infile = open('data/39.txt')
text = infile.read()
infile.close()
tokens = text.split()

#here we call the text cleaning function
words = [w.lower() for w in tokens if w.isalpha()]


I am working on the file "Counting/Counting multi detector Dead TIme.ipynb".
The first task is:
Generate some data
Can you write Python code for it?

np.random.seed(8675309)
Rate1 = 10
Rate2 = 20
deadtime = 0.05

times1 = np.random.exponential(1/Rate1, size=1000)
times2 = np.random.exponential(1/Rate2, size=1000)

times = pd.DataFrame({'between1':times1, 'between2':times2})
times['times1'] = np.cumsum(times['between1'])
times['times2'] = np.cumsum(times['between2'])

# get the times of bunch of hits

fig, ax = plt.subplots(ncols=2, nrows=1, figsize=(20,8), squeeze=False)
print(ax[0][0])
times[['between1', 'between2']].plot(ax=ax[0][0])
ax[0][0].set_ylabel('Time between')
times[['times1', 'times2']].plot(ax=ax[0][1])
ax[0][1].set_ylabel('Wall time')
plt.tight_layout()
plt.figure(figsize=(20,8))
times[['between1', 'between2']].hist(bins=30, figsize=(20,8))

# make cts per unit
realcps1 = np.histogram(times['times1'], bins=np.arange(0, times['times1'].max()))[0]
realcps2 = np.histogram(times['times2'], bins=np.arange(0, times['times2'].max()))[0]

# then cull out all points and are closer than deadtime to each other
times['between1dt'] = times['between1'].copy()
times['between1dt'].loc[times['between1dt'] < deadtime] = np.nan
times['between2dt'] = times['between2'].copy()
times['between2dt'].loc[times['between2dt'] < deadtime] = np.nan

times['times1dt'] = np.cumsum(times['between1dt'])
times['times2dt'] = np.cumsum(times['between2dt'])

times[['times1', 'times1dt']].plot(figsize=(10,7))
times[['times2', 'times2dt']].plot(figsize=(10,7))

dtcps1 = np.histogram(times['times1dt'].dropna(), bins=np.arange(0, times['times1dt'].dropna().max()))[0]
dtcps2 = np.histogram(times['times2dt'].dropna(), bins=np.arange(0, times['times2dt'].dropna().max()))[0]

df = pd.DataFrame({'dtcps1':dtcps1, 'realcps1':realcps1[:len(dtcps1)]})
df.plot()

# TODO looks wrong!!

np.random.seed(8675309)
size = 100
n_rate = 6
data = np.empty((n_rate, size))
for ii, d in enumerate(tb.linspace(1, 100, n_rate)):
    data[ii] = np.random.poisson(d, size=size)
print(data.shape)

plt.plot(data.T);


I am working on the file "Counting/Dead Time corrections.ipynb".
The first task is:
And plot the rates per unit time
Can you write Python code for it?

plt.figure(figsize=(8,6))
h1, b1 = np.histogram(edata, np.arange(1000))
plt.plot(tb.bin_edges_to_center(b1), h1, label='Real data', c='k')

h2, b2 = np.histogram(edata_td1, np.arange(1000))
plt.plot(tb.bin_edges_to_center(b2), h2, label='Small dead time', c='r')

h3, b3 = np.histogram(edata_td2, np.arange(1000))
plt.plot(tb.bin_edges_to_center(b3), h3, label='Large dead time')

plt.legend(bbox_to_anchor=(1, 1))
plt.xlim((0,400))
plt.ylabel('Rate')
plt.xlabel('Time')


I am working on the file "Counting/Dead Time corrections.ipynb".
The first task is:
But this is totally broken!!!
Output data files for each
Can you write Python code for it?

real = pd.Series(edata)
td1 = pd.Series(edata_td1)
td2 = pd.Series(edata_td2)

real.to_csv('no_deadtime_times.csv')
td1.to_csv('small_deadtime_times.csv')
td2.to_csv('large_deadtime_times.csv')

real = pd.Series(h1[h1>0])
td1 = pd.Series(h2[h2>0])
td2 = pd.Series(h3[h3>0])

real.to_csv('no_deadtime_rates.csv')
td1.to_csv('small_deadtime_rates.csv')
td2.to_csv('large_deadtime_rates.csv')


I am working on the file "Counting/Dead Time corrections.ipynb".
The first task is:
Can we use $n_1 = \frac{R_1}{1-R_1 \tau}$ to derive the relation and spread in the dist of R?
Algerbra changes math to: $R_1=\frac{n_1}{1+n_1\tau}$
Use the small dead time
Can you write Python code for it?

# assume R1 is Poisson

with mc.Model() as model:
    tau = deadtime1
    obsRate = mc.Uniform('obsRate', 0, 1000, shape=1)
    obsData = mc.Poisson('obsData', obsRate, observed=h2[:400], shape=1)
    realRate = mc.Deterministic('realRate', obsData/(1-obsData*tau))
    start = mc.find_MAP()
    trace = mc.sample(10000, start=start, njobs=8)

mc.traceplot(trace, combined=True, varnames=('obsRate', ))
mc.summary(trace, varnames=('obsRate', ))

sns.distplot(trace['realRate'].mean(axis=0), bins=10)
plt.xlabel('realRate')
plt.ylabel('Density')

dt1_bounds = np.percentile(trace['realRate'], (2.5, 50, 97.5))
print('The estimate of the real rate given that we know the dead time is:', dt1_bounds,
      (dt1_bounds[2]-dt1_bounds[0])/dt1_bounds[1])

dat_bounds = np.percentile(h1[:400], (2.5, 50, 97.5))
print("This compares with if we measured without dead time as:", dat_bounds,
      (dat_bounds[2]-dat_bounds[0])/dat_bounds[1])


I am working on the file "Counting/Dead Time corrections.ipynb".
The first task is:
Equation 2 gives the expectation and variance of dead time processes.
$E[\tilde{Y}] \sim \frac{\lambda t}{1+\lambda t}$
$Var[\tilde{Y}] \sim \frac{\lambda t}{(1+\lambda \tau)^3}$
$\lambda \sim \frac{E[\tilde{Y}]}{t-E[\tilde{Y}] \tau}$
Lets explore the size of these error bars as compared to no dead time.
Can you write Python code for it?

np.random.seed(8675309)

rate = 40

df = pd.DataFrame({'Poisson':np.random.poisson(rate, 100)})
df['var'] = rate  # property of Poisson
dt = 0.05
df['obs'] = df['Poisson']/(1+df['Poisson']*dt)
df['obsvar'] = (df['Poisson'])/(1+df['Poisson']*dt)**3

df['ratio'] = df['Poisson']/df['obs']
df.mean()

df.head()

plt.figure(figsize=(8,5))
plt.errorbar(range(len(df)), df['Poisson'], yerr=np.sqrt(df['var']), ecolor='k', c='k',label='Poisson')

plt.errorbar(range(len(df)), df['obs'], yerr=np.sqrt(df['obsvar']), ecolor='g', c='g',label='Obs')

plt.legend(bbox_to_anchor=(1, 1))
plt.tight_layout()

plt.figure(figsize=(8,5))
plt.errorbar(range(len(df)), df['Poisson'], yerr=np.sqrt(df['var']), ecolor='k', c='k',label='Poisson')

plt.errorbar(range(len(df)), df['ratio']*df['obs'], yerr=np.sqrt(df['ratio']*df['obsvar']), ecolor='g', c='g',label='Obs')

plt.legend(bbox_to_anchor=(1, 1))
plt.tight_layout()

plt.figure(figsize=(8,5))
plt.plot(range(len(df)), np.sqrt(df['var'])/df['Poisson'], c='k',label='Poisson')
plt.plot(range(len(df)),np.sqrt(df['ratio']*df['obsvar'])/(df['ratio']*df['obs']), c='g',label='Obs')

plt.legend(bbox_to_anchor=(1, 1))
plt.tight_layout()


I am working on the file "Counting/Dead Time corrections.ipynb".
The first task is:
This is consistent with a Poisson of parameter 20! But there seems to be an under prediction going on, wonder why?
Go through Posterior Predictive Checks (http://docs.pymc.io/notebooks/posterior_predictive.html) and see if we are reprodicting the mean and variance.
Can you write Python code for it?

ppc = mc.sample_ppc(trace, samples=500, model=model, size=100)

ax = plt.subplot()
sns.distplot([n.mean() for n in ppc['Poisson']], kde=False, ax=ax)
ax.axvline(cts.mean())
ax.set(title='Posterior predictive of the mean (Poisson)', xlabel='mean(x)', ylabel='Frequency');

ax = plt.subplot()
sns.distplot([n.var() for n in ppc['Poisson']], kde=False, ax=ax)
ax.axvline(cts.var())
ax.set(title='Posterior predictive of the variance (Poisson)', xlabel='var(x)', ylabel='Frequency');

ax = plt.subplot()
sns.distplot([n.mean() for n in ppc['meas']], kde=False, ax=ax)
ax.axvline(np.diff(edata).mean())
ax.set(title='Posterior predictive of the mean (Exponential)', xlabel='mean(x)', ylabel='Frequency');

ax = plt.subplot()
sns.distplot([n.var() for n in ppc['meas']], kde=False, ax=ax)
ax.axvline(np.diff(edata).var())
ax.set(title='Posterior predictive of the variance (Exponential)', xlabel='var(x)', ylabel='Frequency');


I am working on the file "Counting/Dead Time corrections.ipynb".
The first task is:
Use the large dead time
Can you write Python code for it?

# assume R1 is Poisson

with mc.Model() as model:
    tau = deadtime2
    obsRate = mc.Uniform('obsRate', 0, 1000)
    obsData = mc.Poisson('obsData', obsRate, observed=h3[:400])
    realRate = mc.Deterministic('realRate', obsData/(1-obsData*tau))
    start = mc.find_MAP()
    trace = mc.sample(10000, start=start, njobs=8)

mc.traceplot(trace, combined=True, varnames=('obsRate', ))
mc.summary(trace, varnames=('obsRate', ))

sns.distplot(trace['realRate'].mean(axis=0))
plt.xlabel('realRate')
plt.ylabel('Density')

dt2_bounds = np.percentile(trace['realRate'], (2.5, 50, 97.5))
print('The estimate of the real rate given that we know the dead time is:', dt1_bounds,
      (dt2_bounds[2]-dt2_bounds[0])/dt2_bounds[1])

dat_bounds = np.percentile(h1[:400], (2.5, 50, 97.5))
print("This compares with if we measured without dead time as:", dat_bounds,
      (dat_bounds[2]-dat_bounds[0])/dat_bounds[1])


I am working on the file "Counting/Dead Time corrections.ipynb".
The first task is:
We are reprodicting well.
Given the data we generated that will be treated as truth, what would we measure with various deadtime and does teh corection match what we think it should?
Correction should look like $n_1 = \frac{R_1}{1-R_1 \tau}$ where $n_1$ is real rate, $R_1$ is observed rate, and $\tau$ is the dead time.
Take edata from above and strep through from beginning to end only keeping points that are dead time away from the previous point.
Can you write Python code for it?

deadtime1 = 0.005 # small dead time
deadtime2 = 0.1   # large dead time

edata_td1 = []
edata_td1.append(edata[0])
edata_td2 = []
edata_td2.append(edata[0])

for ii, v in enumerate(edata[1:], 1):  # stop one shy to not run over the end, start enumerate at 1
    if v - edata_td1[-1] >= deadtime1:
        edata_td1.append(v)
    if v - edata_td2[-1] >= deadtime2:
        edata_td2.append(v)

edata_td1 = np.asarray(edata_td1)
edata_td2 = np.asarray(edata_td2)

plt.figure(figsize=(8,6))
plt.plot(edata, np.arange(len(edata)), label='Real data')

plt.plot(edata_td1, np.arange(len(edata_td1)), label='Small dead time')
plt.plot(edata_td2, np.arange(len(edata_td2)), label='Large dead time')

plt.xlabel('Time of event')
plt.ylabel('Event number')
plt.title("Modeled underlying data")

plt.legend(bbox_to_anchor=(1, 1))


I am working on the file "Counting/Dead Time corrections.ipynb".
The first task is:
Why in the world is the error smaller on the uncorrected data?
Generate Poisson process data and generate exponential
For each interval choose $n$ events from a Poisson. Then draw from a uniform the location in the interval for each of the events.
Can you write Python code for it?

np.random.seed(8675309)
nT = 400
cts = np.random.poisson(20, size=nT)
edata = []
for i in range(nT):
    edata.extend(i + np.sort(np.random.uniform(low=0, high=1, size=cts[i])))
edata = np.asarray(edata)
edata.shape

plt.plot(edata, np.arange(len(edata)))
plt.xlabel('Time of event')
plt.ylabel('Event number')
plt.title("Modeled underlying data")

with mc.Model() as model:
    lam = mc.Uniform('lambda', 0, 1000)  # this is the exponential parameter
    meas = mc.Exponential('meas', lam, observed=np.diff(edata))
    lam2 = mc.Uniform('lam2', 0, 1000)
    poi = mc.Poisson('Poisson', lam2, observed=cts)
    start = mc.find_MAP()
    trace = mc.sample(10000, start=start, njobs=8)

mc.traceplot(trace, combined=True, lines={'lambda':20, 'lam2':20})
mc.summary(trace)

fig, ax = plt.subplots(ncols=1, nrows=2, sharex=True)
sns.distplot(trace['lambda'], ax=ax[0])
sns.distplot(trace['lam2'], ax=ax[1])
plt.xlabel('Lambda')
ax[0].set_ylabel('Exp')
ax[1].set_ylabel('Poisson')
ax[0].axvline(20, c='r', lw=1)
ax[1].axvline(20, c='r', lw=1)
plt.tight_layout()


I am working on the file "Counting/Poisson and exponential.ipynb".
The first task is:
Can we use $n_1 = \frac{R_1}{1-R_1 \tau}$ to derive the relation and spread in the dist of R?
Algerbra changes math to: $R_1=\frac{n_1}{1+n_1\tau}$
Use the small dead time
Can you write Python code for it?


I am working on the file "Counting/Poisson and exponential.ipynb".
The first task is:
Generate Poisson process data and generate exponential
For each interval choose $n$ events from a Poisson. Then draw from a uniform the location in the interval for each of the events.
Can you write Python code for it?


I am working on the file "Counting/Poisson and exponential.ipynb".
The first task is:
This is consistent with a Poisson of parameter 20! But there seems to be an under prediction going on, wonder why?
Go through Posterior Predictive Checks (http://docs.pymc.io/notebooks/posterior_predictive.html) and see if we are reprodicting the mean and variance.
Can you write Python code for it?


I am working on the file "Counting/Poisson and exponential.ipynb".
The first task is:
Use the large dead time
Can you write Python code for it?


I am working on the file "Counting/Two pulser.ipynb".
The first task is:
Low deadtime case
So with frequencies below the cutoff the formula is:
$\tau = \frac{t}{2} \frac{n_1+n_2-n_{sup}}{n_1n_2}$
Where $n_x$ are the counts per acculation period
Can you write Python code for it?

# make one at 90 and one at 70
pulser1 = np.linspace(0, 400, 400*90)
pulser2 = np.linspace(0, 400, 400*70)
# these are times so we can deadtime correct each one

def deadtime_correct(data, deadtime):
    """
    input is a list of times, measurements are assumed in unit 1 bins
    """
    out = []
    out.append(data[0])
    for ii in range(1, len(data)):
        if data[ii] - out[-1] >= deadtime:
            out.append(data[ii])
    return np.asarray(out)

pulser1_td1 = deadtime_correct(pulser1, deadtime1)
pulser2_td1 = deadtime_correct(pulser2, deadtime1)

pulser12 = np.sort(np.append(pulser1, pulser2))
pulser12_td1 = deadtime_correct(pulser12, deadtime1)

plt.figure(figsize=(8,6))
plt.plot(pulser12, np.arange(len(pulser12)), label='Pulser12')
plt.plot(pulser12_td1, np.arange(len(pulser12_td1)), label='Pulser12 corrected')

plt.plot(pulser1, np.arange(len(pulser1)), label='Pulser1')
plt.plot(pulser1_td1, np.arange(len(pulser1_td1)), label='Pulser1 corrected')

plt.plot(pulser2, np.arange(len(pulser2)), label='Pulser2')
plt.plot(pulser2_td1, np.arange(len(pulser2_td1)), label='Pulser2 corrected')

plt.xlabel('Time of event')
plt.ylabel('Event number')
plt.title("Modeled underlying data")

plt.legend(bbox_to_anchor=(1, 1))


I am working on the file "Counting/Two pulser.ipynb".
The first task is:
Turn up the frequency and see which type the dead time is
Can you write Python code for it?

# make one at 90 and one at 70
pulser1 = np.linspace(0, 400, 400*250)
pulser2 = np.linspace(0, 400, 400*220)
# these are times so we can deadtime correct each one

pulser1_td1 = deadtime_correct(pulser1, deadtime1)
pulser2_td1 = deadtime_correct(pulser2, deadtime1)

pulser12 = np.sort(np.append(pulser1, pulser2))
pulser12_td1 = deadtime_correct(pulser12, deadtime1)

plt.figure(figsize=(8,6))
plt.plot(pulser12, np.arange(len(pulser12)), label='Pulser12')
plt.plot(pulser12_td1, np.arange(len(pulser12_td1)), label='Pulser12 corrected')

plt.plot(pulser1, np.arange(len(pulser1)), label='Pulser1')
plt.plot(pulser1_td1, np.arange(len(pulser1_td1)), label='Pulser1 corrected')

plt.plot(pulser2, np.arange(len(pulser2)), label='Pulser2')
plt.plot(pulser2_td1, np.arange(len(pulser2_td1)), label='Pulser2 corrected')

plt.xlabel('Time of event')
plt.ylabel('Event number')
plt.title("Modeled underlying data")

plt.legend(bbox_to_anchor=(1, 1))


I am working on the file "Counting/Two pulser.ipynb".
The first task is:
Which it is
High deadtime case
Can you write Python code for it?

# make one at 90 and one at 70
pulser1 = np.linspace(0, 400, 400*3)
pulser2 = np.linspace(0, 400, 400*4)
# these are times so we can deadtime correct each one

pulser1_td1 = deadtime_correct(pulser1, deadtime2)
pulser2_td1 = deadtime_correct(pulser2, deadtime2)

pulser12 = np.sort(np.append(pulser1, pulser2))
pulser12_td1 = deadtime_correct(pulser12, deadtime2)

plt.figure(figsize=(8,6))
plt.plot(pulser12, np.arange(len(pulser12)), label='Pulser12')
plt.plot(pulser12_td1, np.arange(len(pulser12_td1)), label='Pulser12 corrected')

plt.plot(pulser1, np.arange(len(pulser1)), label='Pulser1')
plt.plot(pulser1_td1, np.arange(len(pulser1_td1)), label='Pulser1 corrected')

plt.plot(pulser2, np.arange(len(pulser2)), label='Pulser2')
plt.plot(pulser2_td1, np.arange(len(pulser2_td1)), label='Pulser2 corrected')

plt.xlabel('Time of event')
plt.ylabel('Event number')
plt.title("Modeled underlying data")

plt.legend(bbox_to_anchor=(1, 1))


I am working on the file "Counting_Tales.ipynb".
The first task is:
Let's get some basic information about these texts: how long they are and how many unique words occur in each one:
Can you write Python code for it?

import glob
import re

files = {}
for fpath in glob.glob("./texts/*.txt"):
    with open(fpath) as f:
         fixed_text = re.sub("[^a-zA-Z'-]"," ",f.read())
    files[fpath] = (len(fixed_text.split()),len(set(fixed_text.split())))

for fname in sorted(files):
    print fname + '\t' + str(files[fname][0]) + '\t' + str(files[fname][1])


I am working on the file "Cours/09_classification_metrics.ipynb".
The first task is:
Classification accuracy: pourcentage de prédictions correctes, c'est le nombre d'instances correctement prédite sur le nombre d'instances total
Conventions

Dans les problèmes de classification binaire, la classe 0 est considérée comme étant la classe négative et la classe 1 comme étant la classe positive
les méthodes du package metrics de Scikit-learn supposent toujours que le premier paramètre fournit correspond aux vrais valeurs et que le deuxième paramètre correspond aux valeurs prédites
Can you write Python code for it?

# accuracy
from sklearn import metrics
print (metrics.accuracy_score(y_test, y_pred_class))


I am working on the file "Cours/09_classification_metrics.ipynb".
The first task is:
Conclusion:

La matrice de Confusion donne "plus de détails" sur les performances du classifieur
Permet de calculer des metrics, sur lesquels on peut se baser pour effectuer le choix du modèle adéquat pour un problème donné

Exemple de choix de metrics en fonction du problème posé?

Le choix de la metric à utiliser dépend de  l'objectif métier
Detection de Spam (classe positive est "spam"): Optimier la precision ou specificity parceque les faux negatives (spam va dans inbox) sont plus acceptables que les faux positives (non-spam va dans spam). DONC,on essaye de minimiser les Faux positifs => maximiser la précision ou la spécificité
Detection de Transactions frauduleuses  (classe positive est "fraude"): Optimiser pour sensitivity parceque les faux positives (transactions normal détéctées comme frauduleuses) sont plus acceptables que les faux negatives (transactions frauduleuses non detectées). DONC,on essaye de minimiser les Faux négatifs => maximiser la sensibilité

Dans le problème qui nous concerne (Diabète), que faut-il optimiser?
Réponse et pourquoi?
Ajustement du seuil de classification pour de meilleurs performances

Beaucoup de classifieurs ne prédisent pas uniquement 0 ou 1 mais sont aussi capable de prédire le degré d'appartenance à une classe sous forme de probabilité
Par défaut, le seuil utilisé pour transformer une probabilité en 0 ou 1 est égal à 0.5
En modifiant ce seuil, il est possible d'améliorer les performances (sans modifier le modèle) pour le problème posé
Can you write Python code for it?

# afficher les 10 premières prédictions
logreg.predict(X_test)[0:10]

# afficher les degrés d'appartenance (les 10 premiers)
logreg.predict_proba(X_test)[0:10, :]

# afficher les degrés d'appartenance pour la classe 1 (les 10 premiers)
logreg.predict_proba(X_test)[0:10, 1]

# on stocke les degrés d'appartenance pour la classe 1
y_pred_prob = logreg.predict_proba(X_test)[:, 1]

# histogramme des probabilités prédites
plt.hist(y_pred_prob, bins=8)
plt.xlim(0, 1)
plt.title('Histogramme des probabilites predites')
plt.xlabel('Probabilite Predite d etre diabetique')
plt.ylabel('Frequence')


I am working on the file "Cours/09_classification_metrics.ipynb".
The first task is:
Conclusion:

Le Seui peut être modifié afin d'augmenter la sensitivité ou la specificité
Sensitivity et specificity possèdent une relation inverse. Lorsque l'un augmente, l'autre diminue

Courbes ROC (ROC Curves),  Surface sous la courbe ( Area Under the Curve (AUC) )
Question: Ne serait-il pas intéressant de voir de quelle manière la sensitivity et la specificity sont affectées par différents seuils, sans modifier le seuil?
Réponse: Tracer la courbe ROC
Can you write Python code for it?

fpr, tpr, thresholds = metrics.roc_curve(y_test, y_pred_prob)
plt.plot(fpr, tpr)
plt.xlim([0.0, 1.0])
plt.ylim([0.0, 1.0])
plt.title('courbe ROC du classifieur de diabetes')
plt.xlabel('False Positive Rate (1 - Specificity)')
plt.ylabel('True Positive Rate (Sensitivity)')
plt.grid(True)


I am working on the file "Cours/09_classification_metrics.ipynb".
The first task is:
Conclusion:

le taux de prédiction(accuracy) est l'indicateur de performance le plus facile à comprendre
Mais, ne tient pas compte de la distribution des valeurs prédites
Et, ne dit rient sur les "types" d'erreurs que la classifieur fait

Matrice de confusion (Confusion matrix)
Table qui décrit de manière détaillés les performances d'un modèle de classification
Can you write Python code for it?


I am working on the file "Cours/09_classification_metrics.ipynb".
The first task is:
Diminuer le seuil de prédiction du diabète pour augmenter la sensitivity du classifieur
Can you write Python code for it?

# Predire un diabete si la probabilité prédite est supérieure à 0.3
y_pred_class = np.array(y_pred_prob>0.3, dtype=int)

# afficher les 10 premières probabilités prédites
y_pred_prob[0:10]

# afficher les 10 premières classes prédites
y_pred_class[0:10]

# ancienne matrice de confusion (seuil par défaut = 0.5)
print confusion

# nouvelle matrice de confusion (seuil = 0.3)
print metrics.confusion_matrix(y_test, y_pred_class)

# la sensitivity a augmenté (avant sensitivité = 0.24)
print 46 / float(46 + 16)

# la spécificité a diminué (avant spécificité = 0.91)
print 80 / float(80 + 50)


I am working on the file "Cours/09_classification_metrics.ipynb".
The first task is:
Erreur de classification (Classification Error ou Misclassification Rate): pourcentage d'instances incorrectement classifiées
Can you write Python code for it?

print (FP + FN) / float(TP + TN + FP + FN)
print 1 - metrics.accuracy_score(y_test, y_pred_class)


I am working on the file "Cours/09_classification_metrics.ipynb".
The first task is:
La performance du modèle : 0.6927 est presque similaire à celle du modèle Null. On peut donc en conclure sur base de l'indicateur de performance taux de prédiction que notre modèle n'est pas très performant
Afin de mieux comprendre pourquoi notre modèle n'est pas performant, nous allons copmparer visuellement les vrais valeurs avec celles prédites
Can you write Python code for it?

# Afficher les 25 premières valeurs
print 'True:', y_test.values[0:25]
print 'Pred:', y_pred_class[0:25]

#..................Que REMARQUEZ VOUS?

import matplotlib.pyplot as plt
%matplotlib inline

plt.figure(figsize=(8,4))
plt.subplot(1,2,1)
_=plt.hist(y_test.values, color='red', normed=True)
plt.title('Vrais valeurs')
_=plt.ylim(0,10)
plt.subplot(1,2,2)
_=plt.hist(y_pred_class, color ='blue',  normed=True)
plt.title('Valeurs Predites')
_=plt.ylim(0,10)


I am working on the file "Cours/09_classification_metrics.ipynb".
The first task is:
Label   : indique si la personne est diabétique ou non, c'est ce qu'on souhaite prédire
Question: peut-on prédire de manière efficace si une personne est diabétique en fonction des mesures médicales (attributs)?
Can you write Python code for it?

# On définit X et y, on va supposer que nous n'avons que 4 attributs : 'pregnant', 'insulin', 'bmi', 'age'
feature_cols = ['pregnant', 'insulin', 'bmi', 'age']
X = pima[feature_cols]
y = pima.label

# diviser X et y en training and testing
from sklearn.cross_validation import train_test_split
X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.25,
                                                    random_state=0)

# on va apprendre un modèle de régression logistique
from sklearn.linear_model import LogisticRegression
logreg = LogisticRegression()
logreg.fit(X_train, y_train)

# On prédit pour les données de test
y_pred_class = logreg.predict(X_test)


I am working on the file "Cours/09_classification_metrics.ipynb".
The first task is:
Sensibilité (Sensitivity) ou Rappel (Recall) ou "True Positive Rate" : Quand la vrai valeur est positive combien de fois je prédis positif?

La "Sensibilité" du classifieur à detecter les instances positives
Can you write Python code for it?

print TP / float(TP + FN)
print metrics.recall_score(y_test, y_pred_class)


I am working on the file "Cours/09_classification_metrics.ipynb".
The first task is:
Spécificité (Specificity): Quand la vrai valeur est negative, combien de fois je prédis négatif?
Can you write Python code for it?


I am working on the file "Cours/09_classification_metrics.ipynb".
The first task is:
la courbe ROC vous aide à choisir un seuil afin d'avoir un certain équilibre entre la sensitivity et la specificity qui satisfait votre besoin

AUC est la surface se trouvant en dessous de la courbe ROC
Can you write Python code for it?


I am working on the file "Cours02_DILLMANN_ISEP2016.ipynb".
The first task is:
1.2) The Floating Point Accuracy

If  there   is  no  integer  p  such    that    x * (2 ** p)    is  a   whole   number, then    internal    representation  is  always  an  approximaMon
I Suggest   that test   equality    of  floats  should not use exact comparison

~~~ python
    x == y
    # Should be replaced by:
    abs(x-y) < 0.0001 # Is a precision of 1/10000 is enough
~~~

Why    does    print(0.1)  return  0.1, if not exact?  (Python designers   set it  up  this way    to automatically round)

2) The Chain of characters (str)
It is the way we use to store character data. The chains in Python are non-modificable  (immutable instances )of characters. These are sequence objects.
Some usual operations on Chains

|Operation | Interpretation|
|-----|----------|
| s1 = "" | Empty chain |
| s1 = "\n" | Carriage return |
| s2 = "This is ISEP" | Double quote |
| bloc = """...""" | Triple quote is a bloc |
| s1 + s2, s2 * 3 | Concatenation, Repetition |
| s1[i],len(s2) | Index, Lenght |
|s[start:end] | items start through end-1 |
|s[start:]    | items start through the rest of the array |
|s[:end]      | items from the beginning through end-1 |
|s[:]         | a copy of the whole array |
|"a parot is %s" % 'dead'| String formating |
| for x in s2, "mia" in "mama-mia" | Iteration, Substring Searches |
Can you write Python code for it?

s1 = "\n"
print('Hello' + s1 + 'World !')

# This is the traditionnal way for formating strings
situation="a parot is %s" % 'dead' # Note that a str 'situation' has been defined
print(situation)

# This is more modern and practical way, no need to declare any new str
print('a parot is {}'.format('dead'))

'a parot is %s' % 'dead'

"mia" in "mama-mia"

s2='1234'
for x in s2:
    print(x)
    #x=int(x)
    #otherwise x is stays as a string
    print(type(x))

s2 = range(1,4)
for x in s2:
    print(x)
    print(type(x))


I am working on the file "Cours02_DILLMANN_ISEP2016.ipynb".
The first task is:
2.1) Indexing the chain

 +---+---+---+---+---+---+---+
 | S | A | U | S | A | G | E |
 +---+---+---+---+---+---+---+
 0   1   2   3   4   5   6   7
-7  -6  -5  -4  -3  -2  -1

Indexes correspond to the place to hold the sausage from left to right
Can you write Python code for it?

s='sausage'
# Indexing
#First element
print(s[0])
#Last element, same as s[len(s)-1]
print(s[-1])
# Extraction
# from index 1 to 3 not included
print(s[1:3])
# from index 1 to the end
print(s[1:])
# from index 0 to the last element not included
print(s[:-1])


I am working on the file "Cours02_DILLMANN_ISEP2016.ipynb".
The first task is:
2.2) Changing and formating
Chains are non-modifiable, so to change a chain we must define a new one
Can you write Python code for it?


I am working on the file "Cours02_DILLMANN_ISEP2016.ipynb".
The first task is:
5) The Tuples
A tuple (t-uplet) is a sequence of non-modifiable values. The values can be any type, and they are indexed by integers, so in that respect tuples are a lot like lists. The important difference is that tuples are immutable.
 Usual operations on tuples

| Operation | Interpretation |
|-----------|----------------|
| T = tuple() | Declare empty tuple |
| t = 'a', 'b', 'c' | Declaration of a tuple |
| a , b = b, a | Elegant tuple assignment |
| T = ('A',) + t[1:] | Way to replace an element of a tuple |
| * T | Allows to scatter the tuple |
| max(1,2,3) | Gives the maximum of the list of numbers (check min)|
| zip(s, T) | Transposes a string and a list |
| t > T  | Comparision operator |
| t.sort() | Sorting the t |
Can you write Python code for it?

print('Enter the number N, to divide it by D')
N=eval(input('N = '))
D=eval(input('D = '))
quot, rem = divmod(N, D) # Use of tuple assignement
print('The number {0}, divided by {1} can be written {1} times {2} plus {3}'.format(N,D,quot,rem))

t=(7,3)
divmod(* t)

# This imitates the dictionary
# without order

t = [('c', 0), ('b', 1), ('a', 2)]
t.sort()

for letter, number in t:
    print(number, letter)

# Dictionaries and tuples
D = {'a':0, 'b':1, 'c':2}
T = D.items()
print(T)
# Conversely you can use a list of tuples to initialize a new dictionary
t = [('a', 0), ('c', 2), ('b', 1)]
d = dict(t)
print(d)


I am working on the file "Cours02_DILLMANN_ISEP2016.ipynb".
The first task is:
Les methodes sont comme des fonctions, sauf qu'elles sont associés à un objet en particulier Quand vous utilisez des attributs comme append et sort, les objets sont modifiés par effet de bord, et il n'y a donc pas de raison de ré-affecter
~~~ python
L = [['abc', 'truc'], ['def', 'ghi'], 0, 1, 2, 3]
L = L.append(['bidule'])
print(L)
~~~
None
Can you write Python code for it?


I am working on the file "Cours02_DILLMANN_ISEP2016.ipynb".
The first task is:
Some of the above mentioned Useful Commands, can be found for a version 1.5 of Python
http://www.onlamp.com/pub/a/python/excerpt/PythonPocketRef/
6) The Files
exemple : noyeaux-RMN.txt
| Symbol | Name | Sensitivity | Spin | Frequency (MHz) |
|------- |----------------|--------------|--------|---------------|
|   1H   | - Hydrogen     | 5.68E+3       |1/2      |100.000000 |
|   2H    |- Deuterium     |8.21E-3        | 1       |15.35060886|
|   3H    |- Tritium       |1.00E-9       |1/2      |106.663974|
|   3He   |- Helium        |3.26E-3       |1/2      | 76.179437|
Can you write Python code for it?

import re
listfileN='noyeaux-RMN.txt'

f=open(listfileN,'rt')

NUClist=[]
lines=f.readlines()

for  i in lines[0:]:
	(isotope,dash,name,receptivity,spin,freq)=i.split()
	Noyeau=dict(Isotope=isotope,Sensibilité=receptivity,Nombre_de_Spin=spin,Frequence_en_MHZ_à_2350mT=freq)
	NUClist.append(Noyeau)

print(NUClist[0])

Noyeau.keys()


I am working on the file "Cours03_DILLMANN_ISEP2016.ipynb".
The first task is:
1.3 Visibilité des variables
Sur une console, toute variable déclarée par une affectation dans une instruction indépendante est accessible depuis n'importe quel endroit.
Can you write Python code for it?

# Ici on relance le Kernel, ce qui néttoie toute affectation

%reset

My_Variable_Number=42
globals()


I am working on the file "Cours03_DILLMANN_ISEP2016.ipynb".
The first task is:
2 Fonctions
Les fonctions sont indispensables en programmation pour créer des entrées-sorties
2.1 Déclaration des Fonctions
Utilisation du mot clef def
Can you write Python code for it?

# Here a function that prints something visual
# This function has no output variable

def do_twice(f):
    """
    This function has a docstring
    It executes twice the function f
    The program it is used by functions:

    - do_eight()
    - print_posts()
    - print_beams()

    """
    f()
    f()

def do_eight(f):
    """
    Usage:
     do_eight(function)
     It executes eight times the passed function

    Input:
     The function f is passed as a variable
     No global variables are passed

    Local variables
      No local variables are needed

    Dependencies
     The program it is used by functions:

    -print_grid()

    """
    do_twice(f)
    do_twice(f)
    do_twice(f)
    do_twice(f)

def print_beam():
    print('| - - - -',end=" "),

def print_post():
    print('|        ',end=" "),

def print_beams():
    do_twice(print_beam)
    print('|',end="\n")

def print_posts():
    do_twice(print_post)
    print('|',end="\n")

def print_row():
    print_beams()

def print_grid():
    print_row()
    do_eight(print_posts)

Titre1='Premier'
Titre2='Second'
print('|  '+Titre1+' | '+Titre2+'  |')
print_grid()


I am working on the file "Cours03_DILLMANN_ISEP2016.ipynb".
The first task is:
2.2 Utilisation des fonction pour le jeu du Pendu
Can you write Python code for it?

import random

words = ['chicken', 'dog', 'cat', 'mouse', 'frog','horse','pig']

def pick_a_word():
	word_position = random.randint(0, len(words) - 1)
	return words[word_position]

word=pick_a_word()
print('The secret word is "{}" '.format(word))

lives_remaining = 14 #this will become a global variable
guessed_letters = ''


I am working on the file "Cours03_DILLMANN_ISEP2016.ipynb".
The first task is:
Attention return est indispensable pour que cette fonction rende quelque chose
Can you write Python code for it?

# Voici une fonction ne rend rien mais c'est prévu
# “Pass" means this method has not been implemented yet, but this will be the place to do it
def update_agent(agent):
    s='Congratulate '+agent.upper()+' he doubles his salary'
    return s

def time_step(agents):
    for agent in agents:
        s=update_agent(agent)
        print('Case of Agent {}:'.format(agent))
        print(s)
        #On appelle cette fonction à l'intérieur
        #Mais pour le moment je ne sais pas
        #ce que je vais faire avec les agents

agents=['bob','jim','joe']
time_step(agents)

# Voici une fonction ne rend rien mais c'est une ERREUR DE PROGRAMMATION
# “Pass" means this method has not been implemented yet, but this will be the place to do it
def My_function(self):
    My_Variable_Fetiche_Number=4200000000

print('La valeur de ma variable fétiche est {}'.format(My_Variable_Fetiche_Number))


I am working on the file "Cours03_DILLMANN_ISEP2016.ipynb".
The first task is:
Certains blocs introduisent un nouvel espace de nomage
Can you write Python code for it?

# On déclare une variable
My_Variable_Fetiche_Number=42
# Puis on cree une fonction ou cette même variable est déclarée

def f():
    My_Variable_Fetiche_Number=4200000000000000000000
    print('Dans la fonction la valeur de ma variable fétiche est {}'.format(My_Variable_Fetiche_Number))

# On execute la fonction
f()
# On veux savoir quelle est la valeur de la variable
print('La valeur de ma variable fétiche est {}'.format(My_Variable_Fetiche_Number))


I am working on the file "Cours03_DILLMANN_ISEP2016.ipynb".
The first task is:
Maintenant le jeu est complet
Can you write Python code for it?

#!/usr/bin/python
# -*- coding: utf-8 -*-
"""
Created on Tue Sep 20 22:11:59 2016
"""

import random

words = ['chicken', 'dog', 'cat', 'mouse', 'frog']
lives_remaining = 14
guessed_letters = ''

def play():
	word = pick_a_word()
	while True:
		guess = get_guess(word)
		if process_guess(guess, word):
			print('You win! Well Done!')
			break
		if lives_remaining == 0:
			print('You are Hung!')
			print('The word was: ' + word)
			break

def pick_a_word():
	word_position = random.randint(0, len(words) - 1)
	return words[word_position]

def get_guess(word):
	print_word_with_blanks(word)
	print('Lives Remaining: ' + str(lives_remaining))
	guess = input(' Guess a letter or whole word?')
	return guess

def print_word_with_blanks(word):
	display_word = ''
	for letter in word:
		if guessed_letters.find(letter) > -1:
			# letter found
			display_word = display_word + letter
		else:
			# letter not found
			display_word = display_word + '-'
	print(display_word)

def process_guess(guess, word):
	if len(guess) > 1 and len(guess) == len(word):
		return whole_word_guess(guess, word)
	else:
		return single_letter_guess(guess, word)

def whole_word_guess(guess, word):
	global lives_remaining
	if guess.lower() == word.lower():
		return True
	else:
		lives_remaining = lives_remaining - 1
		return False

def single_letter_guess(guess, word):
	global guessed_letters
	global lives_remaining
	if word.find(guess) == -1:
		# letter guess was incorrect
		lives_remaining = lives_remaining - 1
	guessed_letters = guessed_letters + guess.lower()
	if all_letters_guessed(word):
		return True
	return False

def all_letters_guessed(word):
	for letter in word:
		if guessed_letters.find(letter.lower()) == -1:
			return False
	return True

play()

# Here a function that prints something visual
# This function has no output variable

def do_twice(f):
    """
    Usage: It executes twice the function f
    Inputs: It requires a function as argument
    Links: The program it is used by functions:

    - do_eight()
    -...


I am working on the file "Cours03_DILLMANN_ISEP2016.ipynb".
The first task is:
On n'a pas encore gagné... et en plus on voudrait que le joueur puisse entrer une lettre ou un mot complet...
On va maintenat ecrire les fonction single_letter_guess et whole_world_guess
Can you write Python code for it?

def whole_word_guess(guess, word):
	global lives_remaining
	if guess.lower() == word.lower():
		return True
	else:
		lives_remaining = lives_remaining - 1
		return False

def single_letter_guess(guess, word):
	global guessed_letters
	global lives_remaining
	if word.find(guess) == -1:
		# letter guess was incorrect
		lives_remaining = lives_remaining - 1
	guessed_letters = guessed_letters + guess.lower()
	if all_letters_guessed(word):
		return True
	return False

def all_letters_guessed(word):
	for letter in word:
		if guessed_letters.find(letter.lower()) == -1:
			return False
	return True


I am working on the file "Cours03_DILLMANN_ISEP2016.ipynb".
The first task is:
Suposons que l'on veux calculer l'aire d'un cercle $A=\pi.r^2$, où $r$ est le rayon, qui peux être variable et $\pi=3.14159$ pour simplifier.
Can you write Python code for it?

pi=3.14159
r=11.2
A=pi*r**2

print("L'aire du disque de rayon {0} m, est A={1} m^2".format(r,A))
print("l'adresse du rayon est {0}, celle de l'aire est {1}".format(id(r),id(A)))

r=14.3
A=pi*r**2
######## On à changé le rayon
print("L aire du disque de rayon {0} m, est A={1} m^2".format(r,A))
print("l'adresse du rayon est {0}, celle de l'aire est {1}".format(id(r),id(A)))


I am working on the file "Cours03_DILLMANN_ISEP2016.ipynb".
The first task is:
~~~ Python

def print_word_with_blanks(word):
    pass

def get_guess(word):
    print_word_with_blanks(word)
    print('Lives Remaining: ' + str(lives_remaining))
    guess = input(' Guess a letter or whole word?')
    return guess
get_guess(word)
~~~
Can you write Python code for it?

#04_06_hangman_get_guess

import random

words = ['chicken', 'dog', 'cat', 'mouse', 'frog']
lives_remaining = 14

def play():
	word = pick_a_word()
	while True:
		guess = get_guess(word)
		if process_guess(guess, word):
			print('You win! Well Done!')
			break
		if lives_remaining == 0:
			print('You are Hung!')
			print('The word was: ' + word)
			break

def pick_a_word():
	word_position = random.randint(0, len(words) - 1)
	return words[word_position]

def get_guess(word):
	print_word_with_blanks(word)
	print('Lives Remaining: ' + str(lives_remaining))
	guess = input(' Guess a letter or whole word?')
	return guess

def process_guess(guess, word):
	global lives_remaining
	lives_remaining = lives_remaining -1
	return False

def print_word_with_blanks(word):
	print('print_word_with_blanks: not done yet')

play()

guessed_letters=''

def print_word_with_blanks(word):
	display_word = ''
	for letter in word:
		if guessed_letters.find(letter) > -1:
			# letter found
			display_word = display_word + letter
		else:
			# letter not found
			display_word = display_word + '-'
	print(display_word)


I am working on the file "Cours04_DILLMANN_ISEP2016.ipynb".
The first task is:
1.2) Quand n'a t'on pas besoin d'ecrire une fonction ?
Pas besoin de définir de nouvelles fonctions si celles-ci existent déja.
Python dispose d'un grand nombre de librairies de fonctions
mais il se peux que l'on n'ai pas besoin de toutes les fonctions
de cette librairie tout au long du programme....
Donc on a TOUJOURS besoin de connaître les fonctions
Can you write Python code for it?

# Exemple d'appel d'une fonction dans une librairie
from math import log10
# Ici je déclare les variables
signal_power = 50 #Watts
noise_power = 5 #Watts
# Là j'utilise une division entre les variables déclareés
ratio = signal_power / noise_power
# Nous allons utiliser une fonction logarithme
decibels = 10 * log10(ratio)
# voila la sortie
print(decibels)

# Cette operation peux être transformée en fonction
def dB(signal_power,noise_power):
    ratio = signal_power / noise_power
    decibels = 10 * log10(ratio)
    return decibels

#Warning: au moment de l'appeler if faut que le log10 soit défini
from math import log10
signal_power = 50
noise_power = 5
dB(signal_power,noise_power)


I am working on the file "Cours04_DILLMANN_ISEP2016.ipynb".
The first task is:
2) Reprise des exemples de l'introduction en fonctions

Palindrome
La racine carrée
Anneés Bissextiles

Nous alons reprendre les exemples du premier cours mais cette fois nous transformerons tout en fonctions. L'objectif est de montrer la rapidité d'execution, et la modularité que la programmation à l'aide des fonctions est seulle à permettre.
2.1) Le Palindrome
Can you write Python code for it?

"""
Programme : estPalindrome(unMot)
Objectif : test de Palindrome

Entrée : unMot, STR contenant une chaine de charactères

Sortie : True or False (Booléen)

@auteur : VF
"""

def estPalindrome(unMot):
    # Declaration des Variables locales
    estPal = True
    l = len(unMot)
    d = 0
    # On compare les lettres symétriques par rapport au milieu du mot de longueur l
    # qui ont pour indices [d] et [l-1-d], le parcours s'effectue tant que les lettres
    # comparées sont égales et que le milieu n'est pas atteint
    while estPal and d < l/2:
        if unMot[d] == unMot[l-1-d]: d += 1
        else: estPal = False
    return estPal
####################################################
# Test de la fonction
mot = input("Donner un mot : ")
# Boucle conditionnelle
if estPalindrome(mot):
    print(mot, "est un palindrome")
else:
    print(mot, "n'est pas un palindrome")


I am working on the file "Cours04_DILLMANN_ISEP2016.ipynb".
The first task is:
2.2) Le test d'Héron d'Alexandrie
Can you write Python code for it?

def RacineCarree(unNombre_Carre,unNombre_Estimateur):
    # Declaration des Variables locales
    EPS = 0.0000000000001 # précision
    val = unNombre_Carre
    racCarreeVal = unNombre_Estimateur

    while racCarreeVal * racCarreeVal - val < -EPS or \
          racCarreeVal * racCarreeVal - val > EPS:
        # la valeur absolue de la différence est supérieure à un seuil
          racCarreeVal = (racCarreeVal + val / racCarreeVal) / 2
    return racCarreeVal
####################################################
# Test de la fonction
unNombre_Carre = 42
unNombre_Carre=float(unNombre_Carre)
unNombre_Estimateur = input("Première estimation de la racine de {} : ".format(unNombre_Carre))
unNombre_Estimateur=float(unNombre_Estimateur)
print(RacineCarree(unNombre_Carre,unNombre_Estimateur))

42**(1/2)

from math import sqrt
sqrt(42)


I am working on the file "Cours04_DILLMANN_ISEP2016.ipynb".
The first task is:
2.3) Les annees bisextiles
Can you write Python code for it?

def Annees_Bissextiles(annee_debut,annee_fin):
    bissextile=[]
    for b in range(annee_debut,annee_fin+1):
                     if ((b % 4 == 0) and (b % 100 != 0)) or (b % 400 == 0):
                         bissextile.append(b)
    return bissextile
####################################################
annees_a_28_fevrier=Annees_Bissextiles(1992,2021)
print(annees_a_28_fevrier)


I am working on the file "Cours04_DILLMANN_ISEP2016.ipynb".
The first task is:
Utilisation des methodes associés aux listes (les methodes sont des fonctions)
Can you write Python code for it?

# On peux ici se servir le la methode "list" qui va
date=A.list[0]
# On peux ici se servir le la methode "split" qui va separer la chaine de charactères
#(jour,mois,date,heure,fuseau,annee)=date.split() # Dans certains sytèmes
(jour,date,mois,annee,heure,fuseau)=date.split() # Dans d'autres sytèmes
# Ici je travaille en python 3.5
print('En l\'an de grâces %s les étudiants de l\'ISEP on étudié les Fonctions, c\'était le %s du mois \'%s\'.' % (annee, date, mois))

# Comme on voit c'est pas franchement lisible en Français, donc on va traduire...
# On peux utiliser les types que sont les tableaux associatifs appelés "dicts"
#pour associer un mois a son abreviation

mois_Month = {'janvier': 'de janvier',
              'fevrier': 'de février',
              'mars': 'de mars',
              'avril': 'd\'avril',
              'mai':'de mai',
              'juin':'de juin',
              'juillet':'de juillet',
              'août':'d\'août',
              'septembre':'de septembre',
              'octobre':'d\' octobre',
              'novembre':'de novembre',
              'décembre':'de décembre'}
print("En l\'an de grâces {0} les étudiants on étudié les Fonctions, c\'était le {1} du mois {2}." .format(annee, date, mois_Month[mois]))


I am working on the file "Cours05-DILLMANN-ISEP2016.ipynb".
The first task is:
2.1.1) Tables de Vérité
Les Amis
| |les amis|les ennemis|
|-|----|-------|
|de mes amis| sont amis | sont ennemis|
|de mes ennemis| sont ennemis| sont amis|
ou plus simplement

| |+|-|
|-|----|-------|
|+| + | -|
|-| -| +|
ou plus en electronique

| |1|0|
|-|----|-------|
|1| 1 | 0|
|0| 0| 1|
ou en logique

| |True|False|
|-|----|-------|
|True| True | False|
|False| False| True|
Can you write Python code for it?

s="les amis de mes amis sont mes amis"

prop_1 = 'les ennemis'
prop_2 = 'de mes ennemis'
conclusion = 'sont mes amis'

if (prop_1 in s):
    prop_a1 = "+"
else:
    prop_a1 = "-"

if (prop_2 in s):
    prop_a2 = "+"
else:
    prop_a2 = "-"

if (conclusion in s):
    conclusion_a = "+"
else:
    conclusion_a = "-"

print("|  " + prop_a1 + " |  " + prop_a2 + " | alors |  " + conclusion_a +" |" ,end="")


I am working on the file "Cours05-DILLMANN-ISEP2016.ipynb".
The first task is:
| e1 | e2 |  ---> |  r |
|----|----|-------|----|
|  + |  + | alors |  + |
Can you write Python code for it?

sPetit = "rois"
sMoyen = "hummains"
sGrand = "mortels"

premise_majeure = "Tous les "+sMoyen+" sont "+sGrand
premise_mineure = "Tous les "+sPetit+" sont "+sMoyen
conclusion = "Tous "+sPetit+" sont "+sGrand

print("Sylogisme : ")
print(premise_majeure)
print('Or, ',end="")
print(premise_mineure)
print('Donc, ',end="")
print(conclusion)


I am working on the file "Cours06_ROUSSET-DILLMANN-ISEP2016.ipynb".
The first task is:
Exemple n°1 : cette cellule affiche 5 lignes, et pourrai afficher des valeurs comparables à celles-ci :
~~~
Cours semaine 0 : 105.34681237564352
Cours semaine 1 : 115.73138361821448
Cours semaine 2 : 121.08482256990295
Cours semaine 3 : 124.42344691023956
Cours semaine 4 : 115.73450285503783
~~~
A noter si l'on veux absolument les mêmes valeurs, on peut biaiser la fonction random par la méthode seed :
l'instruction random.seed(0) permet de garantir la "reproductibilité" des résultats.
Can you write Python code for it?

import random
random.seed(0)
simulation_boursiere(100, 5, 10 )


I am working on the file "Cours06_ROUSSET-DILLMANN-ISEP2016.ipynb".
The first task is:
Exemple n°2 : cette cellule doit afficher :
~~~
Cours semaine 0 : 32.07693325674235
Cours semaine 1 : 18.53044918097587
Cours semaine 2 : 17.872444811843824
Cours semaine 3 : 12.672627612782238
Cours semaine 4 : 17.60190600299601
Cours semaine 5 : 14.681739640999766
Cours semaine 6 : 33.99446314175473
Cours semaine 7 : 22.772097693761907
Cours semaine 8 : 0
Cours semaine 9 : 9.272486028487437
~~~
A noter le random.seed(7) qui permet de garantir la reproductabilité des résultats, même avec une génération de variable aléatoire
Can you write Python code for it?

import random
random.seed(7)
simulation_boursiere(50, 10, 20 )


I am working on the file "Cours06_ROUSSET-DILLMANN-ISEP2016.ipynb".
The first task is:
Quelques exemples, les résultats ne doivent pas changer (à noter que les consignes sont que le résultat de la fonction ne doit pas changer quelque soit les données d'entrée, pas seulement ces exemples)
Exemple n°1 : affiche 2 2 2 3 5
Can you write Python code for it?


I am working on the file "Cours07-DILLMANN-ISEP2016.ipynb".
The first task is:
2) Correction de fonctions en vrac (les fonction suivantes doivent être corrigées)
2.1) Test des entiers et des premiers
Can you write Python code for it?

def est_entier(x):
    return x == int(x)

def est_premier(n):
    if n < 2:
        return False
    for it in range(2,int(n**0.5)+1):
        if n % it == 0:
            return False
    return True

n=float(input())
print("est entier ? : {}".format(est_entier(n)))
print("est premier ? : {}".format(est_premier(n)))
#Que se passe t'il si l'on ne force pas n a être un nombre  ?
#Que se passe t'il si on a un nombre a virgule (float) ?
#Est ce que ce nombre doit être nécessairement un int ou est ce que cela peut être autre chose ?


I am working on the file "Cours07-DILLMANN-ISEP2016.ipynb".
The first task is:
3) Exercices de simplification
3.1) Exercice 2 : simplification de la fonction est_pair()
Simplifier la fonction suivante, qui renvoit True si un nombre est pair, False sinon.
Indication : On peut en faire une version très très courte.
Can you write Python code for it?

## Référence - à priori ne la modifiez pas, s'il vous plaît
def est_pair(n):
    if n % 2 == 0:
        return True
    else:
        return False

## DM - exercice n°2
## Modifiez le code ci-dessous, et ne modifiez pas ces commentaires
def est_pair(n):
    if n % 2 == 0:
        return True
    else:
        return False


I am working on the file "Cours07-DILLMANN-ISEP2016.ipynb".
The first task is:
3.2) Exercice 2 : fonction a un seul diviseur
Simplifier la fonction suivante, qui renvoit True si un nombre possède 1 et un unique diviseur différent de 1 et lui-même, False sinon.
Pour le coup on ne peut pas beaucoup réduire le code de la fonction, sauf à changer l'algorithme (pour un résultat équivalent). En modifiant l'algorithme, on peut l'écrire en une ligne (en utilisant les bonnes fonctions)
Can you write Python code for it?

## Référence - à priori ne la modifiez pas, s'il vous plaît
def possede_un_seul_diviseur(n):
    nb_diviseur = 0
    for it in range(2,n):
        if n % it == 0:
            nb_diviseur = nb_diviseur + 1
    if nb_diviseur == 1:
        return True
    return False

## DM - exercice n°3
## Modifiez le code ci-dessous, et ne modifiez pas ces commentaires
def possede_un_seul_diviseur(n):
    nb_diviseur = 0
    for it in range(2,n):
        if n % it == 0:
            nb_diviseur = nb_diviseur + 1
    if nb_diviseur == 1:
        return True
    return False


I am working on the file "Cours07-DILLMANN-ISEP2016.ipynb".
The first task is:
3.5) Exercice 5 - fizzbuzz
On définit une foction fizzbuzz, qui prend un argument n et, pour tous les nombres de 1 à n :

affiche fizz si le nombre est divisible par 3
affiche buzz si le nombre est divisible par 5
affiche fizzbuzz si il est à la fois divisible par 3 et 5
affiche le nombre si aucun des cas ci-dessus n'est réalisé

Beaucoup de choses à simplifier dans cette fonction, par contre cela ne se traduira pas forcément par des lignes en moins. on peut quand même gagner quelques lignes.
Can you write Python code for it?

## Référence - à priori ne la modifiez pas, s'il vous plaît
def fizzbuzz(n):
    it = 1
    while it <= n:
        if (it % 3 == 0) and (it % 5 == 0):
            print("fizzbuzz")
        if (it % 3 == 0) and (it % 5 != 0):
            print("fizz")
        if (it % 3 != 0) and (it % 5 == 0):
            print("buzz")
        if (it % 3 != 0) and (it % 5 != 0):
            print(it)
        it = it + 1

## DM - exercice n°6
## Modifiez le code ci-dessous, et ne modifiez pas ces commentaires
def fizzbuzz(n):
    it = 1
    while it <= n:
        if (it % 3 == 0) and (it % 5 == 0):
            print("fizzbuzz")
        if (it % 3 == 0) and (it % 5 != 0):
            print("fizz")
        if (it % 3 != 0) and (it % 5 == 0):
            print("buzz")
        if (it % 3 != 0) and (it % 5 != 0):
            print(it)
        it = it + 1


I am working on the file "Cours07-DILLMANN-ISEP2016.ipynb".
The first task is:
3.7) Exercice 8 - fonction maximum_pair
Simplifiez la fonction suivante qui renvoit le plus grand nombre pair d'une liste ne contenant que des nombres pairs positifs, ou 0 si la liste ne contient aucun nombre pair.
On peut raisonnablement l'écrire en 5 ligne (voir en une ligne avec la list-comprehension, mais elle n'est pas au programme)
Can you write Python code for it?

## Référence - à priori ne la modifiez pas, s'il vous plaît
def maximum_pair(liste):
    for it in liste:
        if it % 2 == 0:
            est_le_plus_grand = True
            for it2 in liste:
                if (it2 % 2 == 0) and it2 > it:
                    est_le_plus_grand = False
                    break
            if est_le_plus_grand == True:
                return it
    return 0

## DM - exercice n°8
## Modifiez le code ci-dessous, et ne modifiez pas ces commentaires
def maximum_pair(liste):
    for it in liste:
        if it % 2 == 0:
            est_le_plus_grand = True
            for it2 in liste:
                if (it2 % 2 == 0) and it2 > it:
                    est_le_plus_grand = False
                    break
            if est_le_plus_grand == True:
                return it
    return 0


I am working on the file "Cours07-DILLMANN-ISEP2016.ipynb".
The first task is:
3.8) Exercice 9 - Fonction carre magique
On code une fonction qui détermine si une liste en entrée correspond à un carré magique de taille 3, c'est à dire qu'il s'agit d'une liste de liste de même longueur, dont les sommes sur les lignes et les colonnes sont égales et tous les termes différents.
Courage : il y a des carres magiques partout dans Paris
Carre Magique Porte d'Auteil et parfois ils sont bien plus compliqués
Can you write Python code for it?

## Référence - à priori ne la modifiez pas, s'il vous plaît
def carre_magique(carre_magique):
    if len(carre_magique) != 3:
        return False

    for it_ligne in carre_magique:
        if len(it_ligne) != 3:
            return False

    for it_ligne_1 in carre_magique:
        for it_ligne_2 in carre_magique:
            if id(it_ligne_1) != id(it_ligne_2):
                for it_elt1 in it_ligne_1:
                    for it_elt2 in it_ligne_2:
                        if it_elt1 == it_elt2:
                            return False

    somme_ligne_1 = 0
    somme_ligne_2 = 0
    somme_ligne_3 = 0
    ligne_1 = carre_magique[0]
    ligne_2 = carre_magique[1]
    ligne_3 = carre_magique[2]

    for it in ligne_1:
        somme_ligne_1 = somme_ligne_1 + it
    for it in ligne_2:
        somme_ligne_2 = somme_ligne_2 + it
    for it in ligne_3:
        somme_ligne_3 = somme_ligne_3 + it

    if (somme_ligne_1 != somme_ligne_2) or (somme_ligne_1 != somme_ligne_3) or (somme_ligne_2 != somme_ligne_3):
        return False

    somme_colonne_1 = 0
    somme_colonne_2 = 0
    somme_colonne_3 = 0

    for it in range(3):
        somme_colonne_1 = somme_colonne_1 + carre_magique[it][0]
    for it in range(3):
        somme_colonne_2 = somme_colonne_2 + carre_magique[it][1]
    for it in range(3):
        somme_colonne_3 = somme_colonne_3 + carre_magique[it][2]

    if (somme_colonne_1 != somme_colonne_2) or (somme_colonne_1 != somme_colonne_3) or (somme_colonne_2 != somme_colonne_3):
        return False

    return True

## DM - exercice n°9
## Modifiez le code ci-dessous, et ne modifiez pas ces commentaires
def carre_magique(carre_magique):
    if len(carre_magique) != 3:
        return False

    for it_ligne in carre_magique:
        if len(it_ligne) != 3:
            return False

    for it_ligne_1 in carre_magique:
        for it_ligne_2 in carre_magique:
            if id(it_ligne_1) != id(it_ligne_2):
                for it_elt1 in it_ligne_1:
    ...


I am working on the file "Cours07-DILLMANN-ISEP2016.ipynb".
The first task is:
La cellule ci-dessous doit afficher C(4,2) => 6, C(6,3) => 20
Can you write Python code for it?

print( "C(4,2) =>", combinatoire(4,2) )
print( "C(6,3) =>", combinatoire(6,3) )


I am working on the file "Cours07-DILLMANN-ISEP2016.ipynb".
The first task is:
La cellule suivante doit afficher 2 => True, 3 => False
Can you write Python code for it?

print( "2 => ", est_pair(2) )
print( "3 => ", est_pair(3) )


I am working on the file "Cours07-DILLMANN-ISEP2016.ipynb".
The first task is:
La cellule suivante doit afficher 4 => True, 6 => False
Can you write Python code for it?

print( "4 => ", possede_un_seul_diviseur(4) )
print( "6 => ", possede_un_seul_diviseur(6) )


I am working on the file "Cours07-DILLMANN-ISEP2016.ipynb".
The first task is:
La cellule suivante doit afficher [6,15,24] et [6,8,10]
Can you write Python code for it?


I am working on the file "Cours07-DILLMANN-ISEP2016.ipynb".
The first task is:
La cellule suivante doit afficher cas 1 => 12, cas 2 => 0
Can you write Python code for it?


I am working on the file "Cours07-DILLMANN-ISEP2016.ipynb".
The first task is:
Maintenant on peux se servir de
%inline matplotlib
import matplotlib.pyplot as plt
pour obennir le graphe de la fonction cube symmetrique par rapport à l'axe y
- quelles sont les modifications de le la fonction cube_positif(x) ?
- de combien de return a t'on besoin ?
Can you write Python code for it?

%matplotlib inline
import matplotlib.pyplot as plt
#On commence sans fonction,

XX=[]
YY=[]
X=range(10,-10,-1)
for x in X:
    XX.append(x)
    YY.append(x*x*x)

plt.plot(XX,YY)

def cube_positif( x ):
    if x*x*x >= 0.0:
        return x*x*x
    elif x*x*x <= 0.0:
        return -1*x*x*x
#On peut simplifier cette fonction

#On va s'en servir de la façon suivante:
XX=[]
YY=[]

X=range(10,-10,-1)
for x in X:
    XX.append(x)
    YY.append(cube_positif( x ))

plt.plot(XX,YY)
plt.show()