Skip to content

Commit

Permalink
Update example_kuramoto_sivashinsky.py
Browse files Browse the repository at this point in the history
Correcting code
  • Loading branch information
dimerf99 committed Dec 16, 2024
1 parent 5412ee6 commit 20cc8ab
Showing 1 changed file with 16 additions and 76 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -9,7 +9,6 @@
import os
import sys
import time
from scipy import interpolate

os.environ['KMP_DUPLICATE_LIB_OK'] = 'TRUE'
sys.path.append(os.path.abspath(os.path.join(os.path.dirname(__file__), '..')))
Expand All @@ -20,82 +19,28 @@
from tedeous.callbacks import early_stopping, plot, cache
from tedeous.optimizers.optimizer import Optimizer
from tedeous.device import solver_device
from tedeous.utils import exact_solution_data


solver_device('gpu')

KS_datapath = "Kuramoto_Sivashinsky.dat"
datapath = "Kuramoto_Sivashinsky.dat"

alpha = 100 / 16
beta = 100 / 16**2
gamma = 100 / 16**4


def func_data(datapath):

t_transpose = True

input_dim = 3
output_dim = 2

def trans_time_data_to_dataset(datapath, ref_data):
data = ref_data
slice = (data.shape[1] - input_dim + 1) // output_dim
assert slice * output_dim == data.shape[
1] - input_dim + 1, "Data shape is not multiple of pde.output_dim"

with open(datapath, "r", encoding='utf-8') as f:
def extract_time(string):
index = string.find("t=")
if index == -1:
return None
return float(string[index + 2:].split(' ')[0])

t = None
for line in f.readlines():
if line.startswith('%') and line.count('@') == slice * output_dim:
t = line.split('@')[1:]
t = list(map(extract_time, t))
if t is None or None in t:
raise ValueError("Reference Data not in Comsol format or does not contain time info")
t = np.array(t[::output_dim])

t, x0 = np.meshgrid(t, data[:, 0])
list_x = [x0.reshape(-1)]
for i in range(1, input_dim - 1):
list_x.append(np.stack([data[:, i] for _ in range(slice)]).T.reshape(-1))
list_x.append(t.reshape(-1))
for i in range(output_dim):
list_x.append(data[:, input_dim - 1 + i::output_dim].reshape(-1))
return np.stack(list_x).T

scale = 1

def transform_fn(data):
data[:, :input_dim] *= scale
return data

def load_ref_data(datapath, transform_fn=None, t_transpose=False):
ref_data = np.loadtxt(datapath, comments="%", encoding='utf-8').astype(np.float32)
if t_transpose:
ref_data = trans_time_data_to_dataset(datapath, ref_data)
if transform_fn is not None:
ref_data = transform_fn(ref_data)
return ref_data

load_ref_data(datapath)
load_ref_data(datapath, transform_fn, t_transpose)

return load_ref_data


def KS_heterogeneous_experiment(grid_res):
exp_dict_list = []

x_min, x_max = 0, 2 * np.pi
y_min, y_max = 0, 2 * np.pi
t_max = 1
grid_res = 20

pde_dim_in = 2
pde_dim_out = 1

domain = Domain()
domain.variable('x', [x_min, x_max], grid_res)
domain.variable('t', [0, t_max], grid_res)
Expand Down Expand Up @@ -145,7 +90,7 @@ def KS_heterogeneous_experiment(grid_res):
neurons = 100

net = torch.nn.Sequential(
torch.nn.Linear(2, neurons),
torch.nn.Linear(pde_dim_in, neurons),
torch.nn.Tanh(),
torch.nn.Linear(neurons, neurons),
torch.nn.Tanh(),
Expand All @@ -155,7 +100,7 @@ def KS_heterogeneous_experiment(grid_res):
torch.nn.Tanh(),
torch.nn.Linear(neurons, neurons),
torch.nn.Tanh(),
torch.nn.Linear(neurons, 1)
torch.nn.Linear(neurons, pde_dim_out)
)

for m in net.modules():
Expand All @@ -169,7 +114,7 @@ def KS_heterogeneous_experiment(grid_res):

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

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

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

Expand All @@ -180,21 +125,24 @@ def KS_heterogeneous_experiment(grid_res):
randomize_parameter=1e-6,
info_string_every=10)

cb_plots = plot.Plots(save_every=50,
cb_plots = plot.Plots(save_every=500,
print_every=None,
img_dir=img_dir,
img_dim='3d') # 3 image dimension options: 3d, 2d, 2d_scatter
img_dim='2d') # 3 image dimension options: 3d, 2d, 2d_scatter

optimizer = Optimizer('Adam', {'lr': 1e-4})

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

end = time.time()

grid = domain.build('NN').to('cuda')
net = net.to('cuda')

error_rmse = torch.sqrt(torch.mean((func_data(grid).reshape(-1, 1) - net(grid)) ** 2))
exact = exact_solution_data(grid, datapath, pde_dim_in, pde_dim_out).reshape(-1, 1)
net_predicted = net(grid)

error_rmse = torch.sqrt(torch.mean((exact - net_predicted) ** 2))

exp_dict_list.append({'grid_res': grid_res, 'time': end - start, 'RMSE': error_rmse.detach().cpu().numpy(),
'type': 'wave_eqn_physical', 'cache': True})
Expand All @@ -221,11 +169,3 @@ def KS_heterogeneous_experiment(grid_res):
# df.boxplot(by='grid_res',column='RMSE',fontsize=42,figsize=(20,10),showfliers=False)
df.to_csv('examples/benchmarking_data/wave_experiment_physical_10_100_cache={}.csv'.format(str(True)))









0 comments on commit 20cc8ab

Please sign in to comment.