Skip to content

Commit

Permalink
init_commit
Browse files Browse the repository at this point in the history
  • Loading branch information
SuperSashka committed May 8, 2024
1 parent 94820b8 commit d08c7c5
Show file tree
Hide file tree
Showing 3 changed files with 115 additions and 6 deletions.
100 changes: 100 additions & 0 deletions examples/example_function_of_model.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,100 @@
import torch
import os
import sys
import matplotlib.pyplot as plt


os.environ['KMP_DUPLICATE_LIB_OK'] = 'TRUE'
sys.path.append(os.path.abspath(os.path.join(os.path.dirname( __file__ ), '..')))

from tedeous.data import Domain, Conditions, Equation
from tedeous.model import Model
from tedeous.callbacks import adaptive_lambda, cache, early_stopping, plot
from tedeous.optimizers.optimizer import Optimizer
from tedeous.device import solver_device

solver_device('cpu')

a = 4


def u(x, a):
return 2*torch.atan(torch.exp(x)*torch.tan(1/2))

def u_xx(x, a):
return (torch.pi * a) ** 2 * torch.sin(torch.pi * a * x)

t0 = 0
tmax = 1
Nt = 99

domain = Domain()

domain.variable('t', [t0, tmax], Nt, dtype='float32')

boundaries = Conditions()

boundaries.dirichlet({'t': 0}, value=1)
#boundaries.dirichlet({'t': 1}, value=0)

grid = domain.variable_dict['t'].reshape(-1,1)

# equation: d2u/dx2 = -16*pi^2*sin(4*pi*x)

equation = Equation()

poisson = {
'd2u/dx2':
{
'coeff': 1,
'term': [0],
'pow': 1,
},

'sin(u)':
{
'coeff': -1,
'term': [None],
'pow': torch.sin,
}
}

equation.add(poisson)

net = torch.nn.Sequential(
torch.nn.Linear(1, 100),
torch.nn.Tanh(),
torch.nn.Linear(100, 100),
torch.nn.Tanh(),
torch.nn.Linear(100, 1)
)

model = Model(net, domain, equation, boundaries)

model.compile('autograd', lambda_operator=1, lambda_bound=17)

img_dir = os.path.join(os.path.dirname( __file__ ), 'function_of_model_img')

cb_cache = cache.Cache(cache_verbose=True, model_randomize_parameter=1e-5)

cb_es = early_stopping.EarlyStopping(eps=1e-5,
loss_window=100,
no_improvement_patience=1000,
patience=5,
info_string_every=1000,
randomize_parameter=1e-5)

cb_plots = plot.Plots(save_every=1000, print_every=None, img_dir=img_dir)

#cb_lambda = adaptive_lambda.AdaptiveLambda()

optimizer = Optimizer('Adam', {'lr': 1e-3}, gamma=0.9, decay_every=1000)

model.train(optimizer, 1e5, save_model=True, callbacks=[cb_cache, cb_es, cb_plots])

plt.plot(grid.detach().numpy(), u(grid,a).detach().numpy(), label='Exact')
plt.plot(grid.detach().numpy(), net(grid).detach().numpy(), '--', label='Predicted')
plt.xlabel('x')
plt.ylabel('y')
plt.legend(loc='upper right')
plt.show()
17 changes: 13 additions & 4 deletions tedeous/derivative.py
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
"""Module of derivative calculations.
"""

from typing import Any, Union, List, Tuple
from typing import Any, Union, List, Tuple,Callable
import numpy as np
from scipy import linalg
import torch
Expand Down Expand Up @@ -49,7 +49,10 @@ def take_derivative(self, term: Union[list, int, torch.Tensor], *args) -> torch.
for k, grid in enumerate(scheme):
grid_sum += self.model(grid)[:, term['var'][j]].reshape(-1, 1)\
* term[dif_dir][1][j][k]
der_term = der_term * grid_sum ** term['pow'][j]
if isinstance(term['pow'][j],(int,float)):
der_term = der_term * grid_sum ** term['pow'][j]
elif isinstance(term['pow'][j],Callable):
der_term = term['pow'][j]( der_term * grid_sum )
der_term = coeff * der_term

return der_term
Expand Down Expand Up @@ -120,7 +123,10 @@ def take_derivative(self, term: dict, grid_points: torch.Tensor) -> torch.Tenso
else:
der = self._nn_autograd(
self.model, grid_points, term['var'][j], axis=derivative)
der_term = der_term * der ** term['pow'][j]
if isinstance(term['pow'][j],(int,float)):
der_term = der_term * der ** term['pow'][j]
elif isinstance(term['pow'][j],Callable):
der_term = term['pow'][j]( der_term * der )
der_term = coeff * der_term

return der_term
Expand Down Expand Up @@ -308,7 +314,10 @@ def take_derivative(self, term: torch.Tensor, grid_points: torch.Tensor) -> torc
continue
h = self._step_h(grid_points)[axis]
prod = self._derivative(prod, h, axis)
der_term = der_term * prod ** term['pow'][j]
if isinstance(term['pow'][j],(int,float)):
der_term = der_term * prod ** term['pow'][j]
elif isinstance(term['pow'][j],Callable):
der_term = term['pow'][j]( der_term * prod )
if callable(term['coeff']) is True:
der_term = term['coeff'](grid_points) * der_term
else:
Expand Down
4 changes: 2 additions & 2 deletions tedeous/input_preprocessing.py
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,7 @@
"""

from copy import deepcopy
from typing import Union
from typing import Union, Callable
import numpy as np
import torch

Expand Down Expand Up @@ -60,7 +60,7 @@ def equation_unify(equation: dict) -> dict:
try:
operator['var']
except:
if isinstance(operator['pow'], (int, float)):
if isinstance(operator['pow'], (int, float, Callable)):
operator[dif_dir] = [operator[dif_dir]]
operator['pow'] = [operator['pow']]
operator['var'] = [0]
Expand Down

0 comments on commit d08c7c5

Please sign in to comment.