#-------------------------------------
# Lecture 11 -- Practice 2. File IO
#-------------------------------------

import numpy as np

# Last time we did a practice problem where we solved the rate equation:
#
#   dA/dt = 1/tau (Ain - A) - k A**2
#
# from t = 0 to t = 10 where Ain = 1, tau = 2, k=0.1, dt = 0.1 and A(t=0) = 0.
#
# (i) Use numpy functions to save t and A as columns 
#     in a text file called "EEsoln_np.dat"
#
# (ii) Use standard python functions to save t and A 
#     as columns in a text file called "EEsoln_py.dat"

Ain = 1
tau = 2
k = 0.1
dt = 0.1
t_final = 10

Nsteps = int(t_final/dt)+1
A = np.zeros(Nsteps)
t = np.zeros(Nsteps)

for n in range(Nsteps-1):
    A[n+1] = A[n] + dt* (1/tau*(Ain-A[n]) - k*A[n]**2)
    t[n+1] = t[n] + dt

print('(i) Saving EEsoln_np.dat')

combined_data = np.vstack((t, A)).T
np.savetxt('EEsoln_np.dat', combined_data)

print('(ii) Saving EEsoln_py.dat')

f1 = open("EEsoln_py.dat", 'w')
for i in range(len(t)):
    f1.write(str(t[i])+' '+str(A[i])+'\n')
f1.close()
