In [28]:
#import os
#os.chdir('/home/aotsvetkov/programms/physlearn')
In [29]:
#os.getcwd()
In [30]:
from physlearn.NeuralNet import NeuralNet
from physlearn.Optimizer import Optimizer
import numpy
import math
import matplotlib.pyplot as plt
from matplotlib import rc
import tensorflow as tf
import scipy
from IPython.display import clear_output
import pickle
%matplotlib inline
In [31]:
#rc('text', usetex=True)
In [32]:
def save_data(folder_name, data, file_name):
cur_dir = os.getcwd()
try:
os.mkdir(folder_name)
except OSError:
pass
os.chdir(folder_name)
with open(file_name, 'wb') as f:
pickle.dump(data, f)
os.chdir(cur_dir)
In [33]:
k = 1.0
m = 1.0
omega_sq = k / m
omega = math.sqrt(omega_sq)
x0 = 0.0
speed0 = 1.0
In [34]:
if (speed0 != 0) and (x0 != 0):
phi0 = math.atan(x0 * omega / speed0)
A = x0 / (math.sin(phi0))
elif (x0 == 0.0) and (speed0 != 0):
phi0 = 0.0
A = speed0 / (omega * math.cos(phi0))
elif (speed0 == 0) and (x0 != 0):
phi0 = math.pi / 2
A = x0 / (math.sin(phi0))
else:
phi0 = 0.0
A = 0
In [35]:
begin_hamiltonian = (k * (x0 ** 2) / 2) + (m * (speed0 ** 2) / 2)
In [36]:
amount_of_points = 30
batch_size = 30
min_time = 0
max_time = 2 * math.pi / math.sqrt(omega_sq)
In [37]:
t_list = numpy.linspace(min_time, max_time, amount_of_points).reshape((1, amount_of_points))
x_expected = A * numpy.sin(omega * t_list + phi0)
In [38]:
t_cv = numpy.linspace(min_time, max_time, 1000).reshape((1, 1000))
In [39]:
net = NeuralNet(-5, 5)
In [40]:
net.add_input_layer(1)
net.add(10, net.sigmoid)
net.add_output_layer(1, net.linear)
In [41]:
net.compile()
In [42]:
dim = net.return_unroll_dim()
In [43]:
def return_cost():
y = net.return_graph()
speed = tf.gradients(y, net.x)[0]
acc = tf.gradients(speed, net.x)[0]
#print(y)
equation_part = tf.reduce_sum((acc + omega_sq * y) ** 2)
begin_part = ((y[0][0] - x0) ** 2) + ((speed[0][0] - speed0) ** 2)
current_hamiltonian = (k * (y ** 2) / 2) + (m * (speed ** 2) / 2)
hamilton_part = tf.reduce_sum((current_hamiltonian - begin_hamiltonian) ** 2)
cost_tensor = begin_part + (1 / amount_of_points) * ((equation_part) + hamilton_part)
return cost_tensor
In [44]:
def cost(params):
net.roll_matrixes(params)
return return_cost()
In [45]:
opt = Optimizer()
In [46]:
opt.params_dict['number_of_individuals'] = 433
opt.params_dict['sess'] = net.sess
opt.params_dict['placeholder'] = net.x
opt.params_dict['x'] = t_list
In [47]:
res = opt.optimize(cost, dim, optimizer=opt.diff_evolution_tf, max_time=200, min_func_value=1e-4)
net.roll_matrixes(res.x)
In [48]:
res
Out[48]:
In [49]:
x_pred = net.run(t_cv)
plt.plot(t_cv[0], x_pred[0])
plt.plot(t_list[0], x_expected[0], 'x')
Out[49]:
In [50]:
plt.plot(res.cost_list)
Out[50]:
In [51]:
time_list = res.misc['time_list']
In [52]:
speed = [i / time_list[i] for i in range(1, len(time_list))]
i_list = [i for i in range(1, len(time_list))]
In [53]:
plt.plot(i_list, speed)
Out[53]:
In [57]:
numpy.arange(5, 448, 16)
Out[57]: