In [19]:
from physlearn.NeuralNet.NeuralNet import NeuralNet
from physlearn.Optimizer import Optimizer
import numpy
import math
import matplotlib.pyplot as plt
import tensorflow as tf
#from calc_percents import calc_percents
%matplotlib inline

In [20]:
k = 1.0
m = 1.0
omega_sq = k / m
omega = math.sqrt(omega_sq)
x0 = 0.0
speed0 = 1.0

In [21]:
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 [22]:
begin_hamiltonian = (k * (x0 ** 2) / 2) + (m * (speed0 ** 2) / 2)

In [23]:
amount_of_points = 30
min_time = 0
max_time = 2 * math.pi / math.sqrt(omega_sq)

In [24]:
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 [25]:
t_cv = numpy.linspace(min_time, max_time, 1000).reshape((1, 1000))

In [26]:
net = NeuralNet(-5, 5)

In [27]:
net.add_input_layer(1)
net.add(10, net.sigmoid)
net.add_output_layer(1, net.linear)

In [28]:
net.compile()

In [29]:
dim = net.return_unroll_dim()

In [30]:
net.enable_numpy_mode()

In [31]:
y = net.return_graph()
speed = tf.gradients(y, net.x)[0]
acc = tf.gradients(speed, net.x)[0]
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)

In [32]:
def cost(params):
    net.roll_matrixes(params)
    return net.calc(cost_tensor, t_list)

In [33]:
net.calc(cost_tensor, t_list)


Out[33]:
1.4975412316629488

In [34]:
opt = Optimizer()

In [35]:
res = opt.optimize(cost, dim, optimizer=opt.diff_evolution, end_cond=60000, min_func_value=1e-12, max_time=100)
net.roll_matrixes(res.x)
res


Out[35]:
Is converge: False
Amount of iterations: 250
Total time: 100.12 s
Reached function value: 0.20858054003546941
Reason of break: Maximum time reached

In [36]:
x_pred = net.run(t_cv)
plt.plot(t_cv[0], x_pred[0])
plt.plot(t_list[0], x_expected[0], 'x')


Out[36]:
[<matplotlib.lines.Line2D at 0x7f12e6628278>]