In [1]:
# Необходмые команды импорта.
import sys
#import os
sys.path.append('../physlearn/')
sys.path.append('../source')
import numpy as np
from numpy import linalg as LA
import tensorflow as tf
from matplotlib import pylab as plt
from IPython.display import clear_output
from physlearn.NeuralNet.NeuralNet import NeuralNet
from physlearn.Optimizer.NelderMead.NelderMead import NelderMead
from CostFunction import CostFunction
import d1_osc
import ann_constructor
import math_util
from visualiser import Visualiser

# Model Parameters
n_hid1 = 7
m = 400 # размер сеток обучения
M = 4 # количество выходных нейронов(базисных функций)
a = -7
b = 7
n_hid2 = 7
%matplotlib inline


D:\Anaconda\lib\site-packages\h5py\__init__.py:36: FutureWarning: Conversion of the second argument of issubdtype from `float` to `np.floating` is deprecated. In future, it will be treated as `np.float64 == np.dtype(float).type`.
  from ._conv import register_converters as _register_converters

In [2]:
# ANN
net, net_output, net_sum, sess = ann_constructor.return_separated_deep_net_expressions(M, n_hid1, n_hid2)
# Выражение, определяющеие образ выходов сети при действии гамильтонианом. Task-dependant
first_deriative = tf.gradients(net_output, net.x)[0]
net_images = (-(tf.gradients(first_deriative, net.x)[0]) + tf.multiply(tf.square(net.x), net.output))
net_images_sum = tf.reduce_sum(input_tensor = net_images, axis = 0)

def net_outs_value(x):
    return net.calc(net_output, {net.x : x})

def net_sum_value(x):
    return net.calc(net_sum, {net.x : x})

def net_images_value(x):
    return net.calc(net_images, {net.x: x})

def net_images_sum_value(x):
    return net.calc(net_images_sum, {net.x: x})

dim = net.return_unroll_dim()
print(dim)


604

In [3]:
cost_function = CostFunction(net)
cost_function.define_approximation_grid(a, b, m)
cost_function.define_linearity_grid(M)
cost_function.compile()
J = cost_function.get_cost_func()

# Оптимизация
opt_nm = NelderMead(-2.5,2.5)
opt_nm.set_epsilon_and_sd(0.3, 100)

In [4]:
optimisation_result = opt_nm.optimize(J, dim, 10**6, 10**(-2))
print("J after optimisation: ", J(optimisation_result.x))
net.roll_matrixes(optimisation_result.x)
print("Ебала: ", optimisation_result)


..   147612 (14%) 147612.000 it\s
---------------------------------------------------------------------------
KeyboardInterrupt                         Traceback (most recent call last)
<ipython-input-4-916b19a5603b> in <module>()
----> 1 optimisation_result = opt_nm.optimize(J, dim, 10**6, 10**(-2))
      2 print("J after optimisation: ", J(optimisation_result.x))
      3 net.roll_matrixes(optimisation_result.x)
      4 print("Ебала: ", optimisation_result)

~\GitKraken\SPBU_COMP_PHYS_NN_QM\physlearn\physlearn\Optimizer\NelderMead\NelderMeadAbstract.py in optimize(self, func, dim, end_cond, min_cost)
    125                 prev_update_time = cur_time
    126 
--> 127             method_type = self.iteration()
    128             self.variance_list.append(numpy.var(self.y_points))
    129             self.types_list.append(method_type)

~\GitKraken\SPBU_COMP_PHYS_NN_QM\physlearn\physlearn\Optimizer\NelderMead\NelderMeadAbstract.py in iteration(self)
    187         self.x_reflected = self.calculate_reflected_point()  # Вычисляем отраженную
    188         # точку
--> 189         y_reflected = self.calc_func(self.x_reflected)
    190         # Далее мы делаем ряд действий, в зависимости от соотношения между значениями функции в найденных точках
    191         # Объяснять подробно нет смысла, так что смотри просто "Метод Нелдера - Мида" в вики

~\GitKraken\SPBU_COMP_PHYS_NN_QM\physlearn\physlearn\Optimizer\NelderMead\NelderMead.py in calc_func(self, params)
      5 
      6     def calc_func(self, params):
----> 7         return self.func(params)

~\GitKraken\SPBU_COMP_PHYS_NN_QM\source\CostFunction.py in J(self, params)
     67     def J(self, params):
     68         self.net.roll_matrixes(params)
---> 69         j = self.net.calc(self.noninvariance_factor, {self.net.x: self.approximation_grid})
     70         j += self.calc_linearity_factor()
     71         j += self.calc_ground_cond_factor()

~\GitKraken\SPBU_COMP_PHYS_NN_QM\physlearn\physlearn\NeuralNet\NeuralNet.py in calc(self, calc_var, d)
    304         """
    305         d.update(self.placeholders_dict)  # Добавляем в словарь d placeholder для матриц весов
--> 306         return self.sess.run(calc_var, d)
    307 
    308     def run(self, inputs):

D:\Anaconda\lib\site-packages\tensorflow\python\client\session.py in run(self, fetches, feed_dict, options, run_metadata)
    875     try:
    876       result = self._run(None, fetches, feed_dict, options_ptr,
--> 877                          run_metadata_ptr)
    878       if run_metadata:
    879         proto_data = tf_session.TF_GetBuffer(run_metadata_ptr)

D:\Anaconda\lib\site-packages\tensorflow\python\client\session.py in _run(self, handle, fetches, feed_dict, options, run_metadata)
   1098     if final_fetches or final_targets or (handle and feed_dict_tensor):
   1099       results = self._do_run(handle, final_targets, final_fetches,
-> 1100                              feed_dict_tensor, options, run_metadata)
   1101     else:
   1102       results = []

D:\Anaconda\lib\site-packages\tensorflow\python\client\session.py in _do_run(self, handle, target_list, fetch_list, feed_dict, options, run_metadata)
   1270     if handle is None:
   1271       return self._do_call(_run_fn, feeds, fetches, targets, options,
-> 1272                            run_metadata)
   1273     else:
   1274       return self._do_call(_prun_fn, handle, feeds, fetches)

D:\Anaconda\lib\site-packages\tensorflow\python\client\session.py in _do_call(self, fn, *args)
   1276   def _do_call(self, fn, *args):
   1277     try:
-> 1278       return fn(*args)
   1279     except errors.OpError as e:
   1280       message = compat.as_text(e.message)

D:\Anaconda\lib\site-packages\tensorflow\python\client\session.py in _run_fn(feed_dict, fetch_list, target_list, options, run_metadata)
   1261       self._extend_graph()
   1262       return self._call_tf_sessionrun(
-> 1263           options, feed_dict, fetch_list, target_list, run_metadata)
   1264 
   1265     def _prun_fn(handle, feed_dict, fetch_list):

D:\Anaconda\lib\site-packages\tensorflow\python\client\session.py in _call_tf_sessionrun(self, options, feed_dict, fetch_list, target_list, run_metadata)
   1348     return tf_session.TF_SessionRun_wrapper(
   1349         self._session, options, feed_dict, fetch_list, target_list,
-> 1350         run_metadata)
   1351 
   1352   def _call_tf_sessionprun(self, handle, feed_dict, fetch_list):

KeyboardInterrupt: 

In [5]:
vis = Visualiser(net, net_output, net_sum, M)
vis.plot_four(np.linspace(-5, 5, m, endpoint=True).reshape(1, m) )


<Figure size 432x288 with 0 Axes>

In [6]:
number_col = M

collocation_grid = math_util.calc_hermite_grid_xi(number_col).reshape(1, number_col)
hamiltonian_matrix = net_images_value(collocation_grid)
bind_matrix = net.run(collocation_grid)
from scipy.linalg import eig
eigvals, eigvecs = eig(hamiltonian_matrix, bind_matrix)
for eigval in eigvals:
    print(eigval)


(-13.83821932883593+0j)
(3.023268077025301+2.127873204180467j)
(3.023268077025301-2.1278732041804673j)
(-0.12994824936298904+0j)

In [7]:
x = np.linspace(0,25,1000)
i = 0

for eigval in eigvals:
    i+=1
    plt.plot(x, eigval+0*x)
    plt.plot(1+i, eigval, 'x')


D:\Anaconda\lib\site-packages\numpy\core\numeric.py:492: ComplexWarning: Casting complex values to real discards the imaginary part
  return array(a, dtype, copy=False, order=order)

In [8]:
np.matmul((net.run(x_obs)).transpose(), np.expand_dims(eigvecs[:,1], -1)).shape


---------------------------------------------------------------------------
NameError                                 Traceback (most recent call last)
<ipython-input-8-65dd87e3a79f> in <module>()
----> 1 np.matmul((net.run(x_obs)).transpose(), np.expand_dims(eigvecs[:,1], -1)).shape

NameError: name 'x_obs' is not defined

In [9]:
x_obs = np.linspace(-3, 3, 100).reshape(1, 100)
for i in range(1,M):
    y = (np.matmul((net.run(x_obs)).transpose(), np.expand_dims(eigvecs[:,1], -1)))#*eigvals[i]
    y1 = np.matmul((net_images_value(x_obs)).transpose(), np.expand_dims(eigvecs[:,1], -1))
    plt.plot(np.sum(x_obs, 0), y )#- y1)


D:\Anaconda\lib\site-packages\numpy\core\numeric.py:492: ComplexWarning: Casting complex values to real discards the imaginary part
  return array(a, dtype, copy=False, order=order)

In [10]:
eigvecs[:,3]


Out[10]:
array([-0.55201824+0.j,  0.69739817+0.j, -0.43710441+0.j,  0.13360907+0.j])

In [11]:
x_obs = np.linspace(-5, 5, 1000).reshape(1, 1000)
k = 3
y = (np.matmul((net.run(x_obs)).transpose(),eigvecs[:,k]))#*eigvals[i]
plt.plot(np.sum(x_obs, 0), y, "b")
y1 = np.matmul((net_images_value(x_obs)).transpose(),eigvecs[:,k])
plt.plot(np.sum(x_obs, 0), y1, "g")
plt.plot(np.sum(x_obs, 0), y - y1,"r--")


D:\Anaconda\lib\site-packages\numpy\core\numeric.py:492: ComplexWarning: Casting complex values to real discards the imaginary part
  return array(a, dtype, copy=False, order=order)
Out[11]:
[<matplotlib.lines.Line2D at 0x1f0635cf278>]

In [12]:
d1_osc.show_wf(1,x_obs)



In [ ]: