Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
Show all changes
153 commits
Select commit Hold shift + click to select a range
b18114f
Add training module
Apr 12, 2019
684f322
Add training script
Apr 12, 2019
567ce20
Implement data parsing
Apr 15, 2019
a270227
initial commit of turing pattern generator
Apr 15, 2019
05ca016
fix bugs and debugging of the solver
Apr 18, 2019
5337429
move rungpu condition to after defintion of yall
Apr 26, 2019
8eb6fcc
generate turing result using cpu
Apr 26, 2019
b79482d
spinodal decomposition
Apr 27, 2019
c4f0839
add the option to reinitialize for each instance
May 1, 2019
ce3f39e
fix bugs in turing_cpu reinitialize
May 1, 2019
fa4c1d8
in turing_cpu, better loading of result to plot samples
May 1, 2019
7e5278f
pca analysis of turing pattern
May 1, 2019
335eee6
update odeimexez on the usage of event function
May 5, 2019
2a0bffa
update turing_ps and turing_cpu after odeimexez update
May 5, 2019
2dd6e0e
generate turing patterns that are close to steady state
May 5, 2019
6eae434
slight modifcation to spdecomp.m for generating spdecomp patterns
May 5, 2019
82af5f5
fix bug in odeimexez, apply transform when et aborts the iteration
May 5, 2019
a102293
post processing of turing pattern
May 5, 2019
8c6f707
post processing
May 8, 2019
6b5e4d6
fix bug in post processing video
May 8, 2019
96d218a
plot dispersion curve
May 13, 2019
56d323a
add DDFT scripts
Jun 28, 2019
70046d8
start adding FSA to odeimex
Jun 29, 2019
ad37036
add moerodeoptions, fix bugs, add output function in odeimex
Jul 1, 2019
622831c
add InterpFcn in odeimex and add ntrp15s
Jul 1, 2019
b970294
test another kernel
Jul 1, 2019
c1f2076
create a nucleus from DDFT
Jul 2, 2019
530756e
start working on Krylov-based DDFT solver
Jul 2, 2019
91131e4
updaet solver_DDFT, and moreode*, seems to work
Jul 3, 2019
e2ba7a5
update solver_DDFT
Jul 3, 2019
bcfb49b
roi diffuse shape function
Jul 3, 2019
0366d53
DDFT_nucleation study nucleation
Jul 3, 2019
7ea11aa
work on solver_DDFT and IP_DDFT
Jul 6, 2019
e12586a
add a few lines in DDFT_nucleation for IP test
Jul 6, 2019
5ec85d7
fix bugs in IP_DDFT and solver_DDFT
Jul 7, 2019
4cd60d7
decrease gmrestol and increase restart in solver_DDFT
Jul 7, 2019
d2d39f6
update DDFT_nucleation, try using real space representation for C
Jul 7, 2019
859a520
use the options of sensFcnMultiplier to directly multiply omega with …
Jul 7, 2019
533c177
fix bugs in solver_DDFT
Jul 8, 2019
e0c6e91
add fminunc option, add Cspace=isotropic option, increase weight by 1…
Jul 8, 2019
b0adbe4
update DDFT_nucleation scripts
Jul 8, 2019
f82c82f
IP_DDFT_debug, plot val and gradient along the search direction
Jul 8, 2019
37a11b7
fix bug in roi_circle
Jul 9, 2019
09e6520
add x_guess input in IP_DDFT, continue from previous run in DDFT_nucl…
Jul 10, 2019
7b95fbd
continue DDFT_nucleation2 from the previous run
Jul 11, 2019
30d4325
add the mode of eval (output model solution) and fval and exitflag ou…
Jul 11, 2019
c25a631
add history_production, producing figures for DDFT IP (need more work)
Jul 11, 2019
5e087bf
visualize DDFT_nucleation2, update DDFT_nucleation2_helper to do opti…
Jul 11, 2019
5af0e2b
update IP_DDFT, add tspan and eval options
Jul 14, 2019
317d33b
add DDFT_nucleation3, a larger alpha, small n0 for nucleation event
Jul 14, 2019
64efb7c
try alternate between 2 datasets DDFT_nucleation3
Jul 14, 2019
9555e50
update solver_DDFT to allow empty C and mu in params
Jul 16, 2019
8285010
switch to custom_EvenPoly for Cspace=isotropic in IP_DDFT
Jul 16, 2019
d47fe29
DDFT_nucleation_PFC, use PFC kernel
Jul 16, 2019
834adad
update IP_DDFT, parameter prescreening and isotropic Cspace, highest …
Jul 16, 2019
e688147
add DDFT_nucleation4 fit DDFT to a 4-th order PFC
Jul 16, 2019
834156a
fix critical bug in jacobian_mult in solver_DDFT, for loop index wron…
Jul 16, 2019
c90e58f
add FDcoeff to compute 1D finite difference coefficient
Jul 16, 2019
5e85688
rewrite Cspace=isotropic, add Cspace=FD
Jul 16, 2019
8ef80df
use parser in solver_DDFT, add option and moreoptions in params, upda…
Jul 16, 2019
0e8d85f
DDFT_nucleation6
Jul 16, 2019
2664bcc
DDFT_nucleation6 and 7
Jul 16, 2019
67dfd83
add Cspace='isotropic_CmE', add optimizing mu params in IP_DDFT
Jul 17, 2019
8656cfa
update and add DDFT_nucleation(4,9)
Jul 17, 2019
1f422b8
DDFT_nucleation15, based on 13, with a different initial guess
Jul 19, 2019
70a568b
if mu is optimized, the constant term in C is removed in IP_DDFT
Jul 19, 2019
a565a77
add the option to optimize D as well
Jul 19, 2019
3cdd8c2
add DDFT_nucleation17 and 18 to test optimizing mu, C, and D at the s…
Jul 19, 2019
3cd783e
DDFT_nucleation19, use 10 frames
Jul 19, 2019
ae2013f
add the option of discrete IP in IP_DDFT, update 19
Jul 19, 2019
cbbb9ea
fix bug in IP_DDFT about the default of D, and set tspan for solver_D…
Jul 19, 2019
af428a5
add mode in IP_DDFT, prepare for post processing
Jul 20, 2019
0bdab36
add DDFT_nucleation files
Jul 20, 2019
2a98340
in IP_DDFT, mode=eval, output modified params and meta for postproces…
Jul 22, 2019
699a60b
update history_production after IP_DDFT update
Jul 22, 2019
7b8e3a9
update DDFT_nucleation13 for visualization
Jul 22, 2019
b2851ff
update history_production to rescale and shift mu and C
Jul 22, 2019
7db47cf
two more files with different initial conditions
Jul 23, 2019
f8957e8
Merge branch 'master' of https://github.com/hbozhao/reacdiff
Jul 23, 2019
852a5c8
add mu_positive option in IP_DDFT, doesn't seem to work at least yet
Jul 23, 2019
f7712aa
add mode='sens' in IP_DDFT
Jul 25, 2019
fb0fc3f
add Cspace='isotropic_cutoff', add assign_suppress options in IP_DDFT
Jul 25, 2019
81eac81
in IP_DDFT, remove isotropic_cutoff, add istropic_cos_cutoff and isot…
Jul 27, 2019
b103af4
DDFT_nucleation26 and 27, try isotropic_poly_scale
Jul 27, 2019
a1bcf79
add istropic_even option in IP_DDFT to use even legendrepolynomials only
Jul 28, 2019
9b74119
DDFT_nucleation28, try isotropic_poly_scale with isotropic_even = true
Jul 28, 2019
36f7fe3
update IP_DDFT, remove shifting by 1 for isotropic_poly, add 29 to te…
Jul 28, 2019
d70e888
Revert "update IP_DDFT, remove shifting by 1 for isotropic_poly, add …
Jul 28, 2019
dbefb76
add isotropic_hermite_scale in IP_DDFT
Jul 28, 2019
4eb1de1
add DDFT_nucleation29 t try isotropic_hermite_scale
Jul 28, 2019
54a5892
upload DDFT_nucleation* on HZ-BazantLab
Jul 29, 2019
a932236
DDFT_nucleation30/31 to test isotropic_hermite_scale with discrete im…
Jul 29, 2019
1db12c0
more DDFT_nucleation32/33 on adding mu while isotropic_hermite_scale
Jul 29, 2019
912931b
visualization of DDFT_nucleation23
Jul 31, 2019
102e1e9
add optional cutoff/scaling for Cspace=isotropic in IP_DDFT
Jul 31, 2019
cc72c43
DDFT_nucleation34 try isotropic with scaling by k0
Jul 31, 2019
c726c25
add Cspace=isotropic_laguerre_scale
Jul 31, 2019
5c4c022
DDFT_nucleation36, sensitivity analysis using isotropic_hermite_scale
Jul 31, 2019
f32919b
Merge branch 'master' of https://github.com/hbozhao/reacdiff
Jul 31, 2019
9d2e663
update IP_DDFT, now cutoff can be used for all Cspace=isotropic*, add…
Jul 31, 2019
ff857f8
in history_production, generalize C to all isotropic*, fix bugs
Jul 31, 2019
6d41919
add DDFT_nucleation30 visualization
Jul 31, 2019
b043639
small updates to DDFT_nucleation files
Jul 31, 2019
b686b25
add isotropic_fourier_scale in IP_DDFT
Aug 2, 2019
3aaeeba
update IP_DDFT, add mode='pp'
Aug 2, 2019
2825717
add history_func, copied from history_production to plot functions in…
Aug 2, 2019
ab3dd92
begin working on mainFigure
Aug 2, 2019
b8005e6
update DDFT_nucleation, add 35: laguerre poly (failed), 37: sensitivi…
Aug 2, 2019
fe826c0
fix bug in IP_DDFT regarding isotropic_fourier_scale
Aug 2, 2019
230a877
update history_production, use history_func
Aug 2, 2019
7c29608
DDFT_nucleation38 try Laguerre polynomials for sensitivity analysis
Aug 2, 2019
a9b7b34
update DDFT_nucleation26/38 to show C2 error bar
Aug 3, 2019
e9781a5
calculate sensitivity (eigenvalue etc) using 1D approx
Aug 5, 2019
9420010
update mainFig and history_func
Aug 5, 2019
aee2537
update DDFT_nucleation36/38 (sensitivity) visualization
Aug 5, 2019
d0a790f
update mainFig and utility function
Aug 13, 2019
f7b4006
DDFT_nucleation39, using initial and final frames only
Aug 14, 2019
bb4b5d8
Merge branch 'master' of https://github.com/hbozhao/reacdiff
Aug 14, 2019
34701fe
critical bug in ASA (adjoint jacobian) for solver_DDFT (reconfirm), L…
Aug 14, 2019
0d5958a
add DDFT_nucleation40, try Cspace = k again after fixing ASA bug
Aug 14, 2019
6470f69
update mainFig, (remove yyaxis right in the bottom row)
Aug 14, 2019
817f412
update mainFig's subplot spacing, figure saved as DDFT_mainFig_v4
Sep 22, 2019
6e4d6f4
add DDFT_nucleation41, redo DDFT_nucleation32 with a different x_guess
Nov 23, 2019
56aebdc
add option of (commented now) shifting C2 such that C2(0) matches the…
Nov 25, 2019
bbfa6de
highlight the difference between row 3 (model) and row 1 (data) using…
Nov 25, 2019
9c91978
fix bug in history_production, add the option of showModelSolution, n…
Nov 25, 2019
4acb8fd
plot the result of DDFT_nucleation32 and 41
Nov 25, 2019
3225464
in history_production, save nonexistent model prediction to result as y
Nov 26, 2019
8ebd596
update mainFig subplot positions, used to produce DDFT_mainFig_v5 on …
Nov 26, 2019
dd3f5df
update history_production, add stparg option, fix xlabel
Nov 26, 2019
38ddee6
visualize DDFT_nucleation41 result
Nov 26, 2019
693b6ec
add user-defined option in Cspace 'user'
May 17, 2020
28fc081
add DDFT_nucleation30_DILI, perform DILI based on nucleation30, (main…
May 17, 2020
680b8da
DDFT_nucleation30_DILI, fix bug, change back to normalized hermite fu…
May 17, 2020
ab57b75
add mode='fgh' in IP_DDFT (for DILI)
May 17, 2020
ded8b76
update DDFT_nucleation30_DILI visualization to generate Fig. 2 in exp…
May 28, 2020
9389b61
add presentation_RD, to generate figure for slide
Jan 4, 2021
91034b8
fux bugs in solver_DDFT
Jan 4, 2021
c7f2837
fix bug in solver_DDFT about user options setting
Jan 5, 2021
00c2015
update presentation_RD.m
Jan 15, 2021
e8c66d4
add presentation_RD_nucleus, present crystallization starting from a …
Jan 16, 2021
c6ad219
update presentation_RD_nucleus, running model and exporting
Jan 16, 2021
bcd99bb
write C3 into an image in presentation_RD_nucleus
Jan 16, 2021
4912d8a
add history_production and history_func, add offset and muderiv options
Jan 16, 2021
39afacc
add history_movie, turn history into a movie
Jan 16, 2021
4bd5f7c
update IP_DDFT, add loss in fgh mode
Jan 16, 2021
b35cdaf
update visualization, generate history movie, dark mode
Jan 16, 2021
730e6c8
add DDFT_nucleation42 created on bgs
Dec 30, 2021
345ba88
Merge branch 'master' of github.com:hbozhao/reacdiff
Dec 30, 2021
231476e
add files on workstation
Dec 30, 2021
ae88762
add DDFT_nucleus.mat on workstation
Dec 30, 2021
ced5709
commit changes on home PC
Dec 30, 2021
0ee2cc5
commit changes on MIT laptop
Dec 30, 2021
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
9 changes: 9 additions & 0 deletions prepare_data.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,9 @@
#!/usr/bin/env python

import reacdiff.parsing as parsing
import reacdiff.data.preprocess as preprocess


if __name__ == '__main__':
args = parsing.parse_dataprep_args()
preprocess.preprocess(args.data_path)
20 changes: 13 additions & 7 deletions reacdiff/data/data.py
Original file line number Diff line number Diff line change
@@ -1,3 +1,4 @@
import h5py
import numpy as np

import reacdiff.utils as utils
Expand Down Expand Up @@ -49,16 +50,21 @@ def __getitem__(self, item):
return Dataset(self.data[item], self.targets[item], self.data2[item])


def load_data(path, targets=False):
if targets:
return np.random.rand(100, 26)
data = np.random.rand(100, 50, 128, 128)
data = np.expand_dims(data, axis=-1)
def load_data(path, max_read=None, key='data'):
"""
:param path: An HDF5 file.
:param max_read: Maximum number of samples to read.
:param key: Data key in HDF5 file.
:return: Numpy array of data
"""
with h5py.File(path, 'r') as f:
data = f[key][:] if max_read is None else f[key][:max_read]
return data


def save_data(data, path):
raise NotImplementedError
def save_data(data, path, key='data'):
with h5py.File(path, 'w') as f:
f.create_dataset(key, data=data)


def split_data(data, splits=(0.9, 0.05, 0.05), seed=None):
Expand Down
34 changes: 34 additions & 0 deletions reacdiff/data/preprocess.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,34 @@
import os

import h5py
import numpy as np

import reacdiff.data.data as datamod


def preprocess(path):
"""
:param path: An HDF5 file.
"""
f = h5py.File(path, 'r')
targets = f['A1']
states = f['y']

assert len(targets.shape) == 2
assert len(states.shape) == 5
assert states.shape[0] == 2

targets = targets[:]
states = states[:]
targets = np.swapaxes(targets, 0, 1)
states = np.transpose(states, (0, 4, 1, 2, 3))
data, data2 = np.expand_dims(states, axis=-1)

name = os.path.splitext(path)[0]
targets_path = name + '_targets.h5'
data_path = name + '_states.h5'
data_path2 = name + '_states2.h5'

datamod.save_data(targets, targets_path)
datamod.save_data(data, data_path)
datamod.save_data(data2, data_path2)
89 changes: 89 additions & 0 deletions reacdiff/parsing.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,89 @@
import argparse
import os


def parse_dataprep_args():
parser = argparse.ArgumentParser(
formatter_class=argparse.ArgumentDefaultsHelpFormatter
)
parser.add_argument('--data_path', type=str, required=True,
help='Path to HDF5 data file')
return parser.parse_args()


def parse_train_args():
parser = argparse.ArgumentParser(
formatter_class=argparse.ArgumentDefaultsHelpFormatter
)

# General arguments
parser.add_argument('--data_path', type=str, required=True,
help='Path to data containing observable states')
parser.add_argument('--targets_path', type=str, required=True,
help='Path to targets')
parser.add_argument('--data_path2', type=str,
help='Path to data containing additional observable states')
parser.add_argument('--save_dir', type=str, default=os.getcwd(),
help='Directory where model checkpoints will be saved')
parser.add_argument('--splits', type=float, nargs=3, default=[0.9, 0.05, 0.05],
help='Split proportions for train/validation/test sets')
parser.add_argument('--save_test_data', action='store_true',
help='Save test data and targets to file')
parser.add_argument('--test_data_path', type=str,
help='Path to separate test data')
parser.add_argument('--test_targets_path', type=str,
help='Path to separate test targets')
parser.add_argument('--test_data_path2', type=str,
help='Path to separate test data for additional observable')
parser.add_argument('--quiet', action='store_true',
help='Do not print model details and batch information during training')
parser.add_argument('--cpu', action='store_true',
help='Run on CPU instead of GPU')
parser.add_argument('--seed', type=int, default=7,
help='Random seed for reproducibility')

# Training arguments
parser.add_argument('--batch_size', type=int, default=32,
help='Batch size')
parser.add_argument('--epochs', type=int, default=30,
help='Maximum number of epochs to run')
parser.add_argument('--lr_start', type=float, default=1e-3,
help='Initial learning rate')
parser.add_argument('--lr_end', type=float, default=1e-4,
help='Final learning rate')
parser.add_argument('--patience', type=int, default=5,
help='Number of epochs without improvement after which training will be stopped')
parser.add_argument('--max_norm', type=float, default=2.0,
help='Maximum gradient norm before clipping occurs')

# Encoder arguments
parser.add_argument('--feat_maps', type=int, default=16,
help='Number of feature maps in first convolutional layer')
parser.add_argument('--first_conv_size', type=int, default=7,
help='Filter size in first convolutional layer')
parser.add_argument('--first_conv_stride', type=int, default=2,
help='Strides in first convolutional layer')
parser.add_argument('--first_pool_size', type=int, default=3,
help='Window size in first pool')
parser.add_argument('--first_pool_stride', type=int, default=2,
help='Strides in first pool')
parser.add_argument('--growth_rate', type=int, default=12,
help='Growth rate in dense blocks')
parser.add_argument('--blocks', type=int, nargs='+', default=[3, 4, 5],
help='Numbers of layers in each dense block')
parser.add_argument('--dropout', type=float, default=0.0,
help='Dropout rate after convolutions')
parser.add_argument('--reduction', type=float, default=0.5,
help='Compression rate in transition blocks')
parser.add_argument('--no_bottleneck', action='store_true',
help='Do not use bottleneck convolution in dense blocks')
parser.add_argument('--flatten_last', action='store_true',
help='Flatten instead of global pool before output')

# RNN arguments
parser.add_argument('--rnn_layers', type=int, default=1,
help='Number of RNN layers')
parser.add_argument('--rnn_units', type=int, default=100,
help='Number of units in RNN')

return parser.parse_args()
Empty file added reacdiff/train/__init__.py
Empty file.
77 changes: 77 additions & 0 deletions reacdiff/train/run_training.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,77 @@
import os

import reacdiff.data.data as datamod
import reacdiff.models.crnn as models
import reacdiff.train.train as train


def run_training(args):
# Load data
print('Loading data')
data = datamod.Dataset(
datamod.load_data(args.data_path),
datamod.load_data(args.targets_path),
None if args.data_path2 is None else datamod.load_data(args.data_path2)
)

# Split data
print(f'Splitting data with seed {args.seed}')
train_data, val_data, test_data = datamod.split_data(data, splits=args.splits, seed=args.seed)

if args.test_data_path is not None and args.test_targets_path is not None:
test_data = datamod.Dataset(
datamod.load_data(args.test_data_path),
datamod.load_data(args.test_targets_path),
None if args.test_data_path2 is None else datamod.load_data(args.test_data_path2)
)

os.makedirs(args.save_dir, exist_ok=True)

if args.save_test_data:
test_data.save(os.path.join(args.save_dir, 'test'))

print(f'Train size = {len(train_data):,} | val size = {len(val_data):,} | test size = {len(test_data):,}')

# Build model
crnn = models.CRNN(
time_steps=train_data.data.shape[1],
input_shape=train_data.data.shape[2:],
output_dim=train_data.targets.shape[1],
observables=train_data.get_num_observables(),
rnn_layers=args.rnn_layers,
rnn_units=args.rnn_units,
use_gpu=not args.cpu
)
crnn.build(
feat_maps=args.feat_maps,
first_conv_size=args.first_conv_size,
first_conv_stride=args.first_conv_stride,
first_pool_size=args.first_pool_size,
first_pool_stride=args.first_pool_stride,
growth_rate=args.growth_rate,
blocks=args.blocks,
dropout=args.dropout,
reduction=args.reduction,
bottleneck=not args.no_bottleneck,
flatten_last=args.flatten_last
)

model_dir = os.path.join(args.save_dir, 'model')
os.makedirs(model_dir, exist_ok=True)

# Train model
train.train(crnn, train_data, model_dir,
batch_size=args.batch_size,
epochs=args.epochs,
val_data=val_data,
patience=args.patience,
lr_start=args.lr_start,
lr_end=args.lr_end,
max_norm=args.max_norm,
quiet=args.quiet)

# Evaluate on test set
print('Evaluating test data')
metrics = crnn.model.evaluate(test_data.get_data(), test_data.targets,
batch_size=args.batch_size)
print(*(f'{name}: {metric:.4f}' for name, metric in zip(crnn.model.metrics_names, metrics)), sep='; ')
59 changes: 59 additions & 0 deletions reacdiff/train/train.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,59 @@
import os

import keras

import reacdiff.utils as utils


def train(crnn, data, save_dir,
batch_size=32,
epochs=30,
val_data=None,
patience=5,
lr_start=1e-3,
lr_end=1e-4,
max_norm=2.0,
quiet=False):
"""
:param crnn: CRNN instance.
:param data: Training data.
:param save_dir: directory to save models to.
:param batch_size: int, batch size.
:param epochs: maximum number of epochs.
:param val_data: Validation data.
:param patience: patience.
:param lr_start: float, initial learning rate.
:param lr_end: float, final learning rate.
:param max_norm: float, maximum gradient norm.
:param quiet: bool, print less information
"""
optimizer = keras.optimizers.Adam(lr=lr_start, clipnorm=max_norm)
crnn.model.compile(optimizer=optimizer, loss='mse', metrics=[utils.rmse, utils.mae])
if not quiet:
crnn.encoder.summary()
crnn.rnn.summary()
crnn.model.summary()

model_name = 'model.{epoch:03d}.h5'
model_path = os.path.join(save_dir, model_name)

def lr_schedule(epoch, _):
return lr_start * ((lr_end / lr_start) ** (epoch / epochs))

checkpoint = keras.callbacks.ModelCheckpoint(filepath=model_path,
verbose=1,
save_best_only=True)
early_stopping = keras.callbacks.EarlyStopping(patience=patience,
verbose=1,
restore_best_weights=True)
lr_scheduler = keras.callbacks.LearningRateScheduler(lr_schedule,
verbose=1)
callbacks = [checkpoint, early_stopping, lr_scheduler]

crnn.model.fit(data.get_data(), data.targets,
batch_size=batch_size,
epochs=epochs,
validation_data=(val_data.get_data(), val_data.targets),
shuffle=True,
verbose=2 if quiet else 1,
callbacks=callbacks)
51 changes: 51 additions & 0 deletions solver/DDFT.m
Original file line number Diff line number Diff line change
@@ -0,0 +1,51 @@
%parameter search
L = [5,5]*2;
N = [256,256]*2;
n = prod(N);
n0 = 0.07;
sigma = 0.01;

rng(1);
n0 = n0 + sigma*randn(N);
y0 = fftn(n0);
y0 = y0(:);
% y00 = y0(1);
% y0(1) = [];

% %use image?
% im = imread('cameraman.tif');
% im = imresize(im,N);
% C2 = fft(im);
% C2 = C2(:);
% C2(1) = 0;
% C2 = C2/max(abs(C2))/1.5;

[k2,k] = formk(N,L);
k2 = k2(:);
% k2(1) = [];

kind1 = k{1}; kind2 = k{2};
[kind1,kind2] = ndgrid(kind1(:),kind2(:));
theta = angle(kind1+i*kind2);

theta = theta(:);

k0 = 10;
alpha = 2;
C2 = exp(-(sqrt(k2)-k0).^2/(2*alpha^2));
C22 = C2;
% C22 = C2 .* (1+cos(theta))/2;
% C22 = C2 .* (exp(-(theta-pi/2).^2/(2*(50/180*pi)^2))+exp(-(theta+pi/2).^2/(2*(50/180*pi)^2)))/2;
J = -k2.*(-C22);

tspan = linspace(0,0.14,100);
tspan = [0,1.7];
tspan = linspace(0,1.07,100);
% tspan = [0,0.14];
options = odeset('AbsTol',1e-3);
[tout,yout] = odeimex(@(t,y) DDFT_nlin(t,y,k2,N),J,tspan,y0);
% Nt = 10000;
% h = (tspan(end)-tspan(1))/Nt;
% [tout,yout] = odeimexez(@(t,y) DDFT_nlin(t,y,k2,N),J,h,Nt,y0,[],1:100:Nt);

figure; k2real(yout(:,end),N);
17 changes: 17 additions & 0 deletions solver/DDFT_nlin.m
Original file line number Diff line number Diff line change
@@ -0,0 +1,17 @@
function dy = DDFT_nlin(t,y,k2,N,y00)
if nargin > 4 && ~isempty(y00)
%k=0 component is omitted
k0flag = true;
y = [y00;y(:)];
else
k0flag = false;
end
y = real(ifftn(reshape(y,N)));
% mu = y - y.^2/2 + y.^3/3;
mu = log(1+y);
fmu = reshape(fftn(mu,N),[],1);
if k0flag
fmu(1) = [];
end
dy = -k2 .* fmu;
end
Loading