<jupyter_start><jupyter_text>Task 2: Approximating linear vector fields<jupyter_code># Load x0 and print shape
x0 = np.loadtxt(fname="linear_vectorfield_data_x0.txt")
print('x0: '+str(np.shape(x0)))
# Load x1 and print shape
x1 = np.loadtxt(fname="linear_vectorfield_data_x1.txt")
print('x1: '+str(np.shape(x1)))<jupyter_output>x0: (1000, 2)
x1: (1000, 2)<jupyter_text>Visualization of the dataset<jupyter_code>plt.figure(figsize=(6,6))
plt.plot(x0[:,0], x0[:,1],'bo', color='blue', linestyle=' ', markersize=2)
plt.plot(x1[:,0], x1[:,1],'o', color='orange', linestyle=' ', markersize=2)
plt.legend(['$x_0$', '$x_1$'])
plt.xlabel('coordinate 1')
plt.ylabel('coordinate 2')<jupyter_output><empty_output><jupyter_text>Visualization of the vector field estimation<jupyter_code>delta_t = 1
v_est = (x1 - x0) / delta_t
plt.figure(figsize=(6,6))
plt.quiver(x0[:,0], x0[:,1], v_est.T[0], v_est.T[1], color='teal')<jupyter_output><empty_output><jupyter_text>Approximation of the matrix A and computation of the MSE<jupyter_code># compute A using closed form solution to minimize least squares error
A = np.linalg.lstsq(x0, v_est, rcond=None)[0]
print(A)
delta_t = 0.1
x1_est = delta_t * (x0 @ A) + x0 #formula: x1_est = delta_t * (x0 @ A)

# print mean squared error between data and approximated function values
MSE_A_lin = np.mean((x1_est - x1)**2)
print('MSE: %.18f' %(MSE_A_lin))

# plot function over data set
plt.scatter(x0, x1, c='blue', s=1, alpha=1, label='Data')
plt.scatter(x0, x1_est, c='red', s=1, alpha=1, label='Approximated function')
plt.xlabel('x')
plt.ylabel('f(x)')
plt.legend()
plt.show()<jupyter_output>MSE: 0.001975851787073813<jupyter_text>Visualization of the trajectory of the point (10, 10)<jupyter_code># create grid out of linearly spaced points from x and y arrays
x, y = np.meshgrid(np.linspace(-10, 10, 50), np.linspace(-10, 10, 50))

# phase portrait and trajectory
u = A[0][0] * x + A[1][0] * y
v = A[0][1] * x + A[1][1] * y

traj = list()
T = 100
x0_n = [10, 10]
for i in range(int(T/delta_t)):
    traj.append(x0_n)
    x0_n = delta_t * (x0_n @ A) + x0_n
traj = np.asarray(traj).T

plt.figure(figsize=(6,6))
plt.streamplot(x, y, u, v, linewidth=0.8)
plt.plot(traj[0], traj[1])<jupyter_output><empty_output>
{'fraction_non_alphanumeric': 0.18128916741271262, 'fraction_numerical': 0.05953446732318711, 'mean_word_length': 6.303921568627451, 'pattern_counts': {'":': 0, '<': 19, '<?xml version=': 0, '>': 19, 'https://': 0, 'lorem ipsum': 0, 'www.': 0, 'xml': 0}, 'pii_count': 0, 'substrings_counts': 0, 'word_list_counts': {'cursed_substrings.json': 0, 'profanity_word_list.json': 0, 'sexual_word_list.json': 0, 'zh_pornsignals.json': 0}}
{'chain_length': '5', 'dir': 'jupyter-structured-clean-dedup', 'id': '202611', 'license': 'MIT', 'n_tokens_mistral': 1032, 'n_tokens_neox': 959, 'n_words': 209, 'path': 'Exercise_5/Task_2.ipynb', 'repo_name': 'Schnursenkel/mlcms_group_g', 'size': '2234'}