-
-
Notifications
You must be signed in to change notification settings - Fork 91
/
Copy pathhamilton_jacobi_et.jmd
237 lines (183 loc) · 8.95 KB
/
hamilton_jacobi_et.jmd
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
---
title: Hamilton-Jacobi PDE Physics-Informed Neural Network (PINN) Loss Function Error vs Time Benchmarks
author: Kirill Zubov, Zoe McCarthy, Yingbo Ma, Francesco Calisto, Valerio Pagliarino, Simone Azeglio, Luca Bottero, Emmanuel Luján, Valentin Sulzer, Ashutosh Bharambe, Nand Vinchhi, Kaushik Balakrishnan, Devesh Upadhyay, Chris Rackauckas
---
Adapted from [NeuralPDE: Automating Physics-Informed Neural Networks (PINNs) with Error Approximations](https://arxiv.org/abs/2107.09443).
Uses the [NeuralPDE.jl](https://neuralpde.sciml.ai/dev/) library from the
[SciML Scientific Machine Learning Open Source Organization](https://sciml.ai/)
for the implementation of physics-informed neural networks (PINNs) and other
science-guided AI techniques.
```julia
using NeuralPDE
using Integrals, Cubature, Cuba
using ModelingToolkit, Optimization, OptimizationOptimJL
using Lux, Plots
using OptimizationOptimisers
using DelimitedFiles
using QuasiMonteCarlo
import ModelingToolkit: Interval, infimum, supremum
```
```julia
function hamilton_jacobi(strategy, minimizer, maxIters)
## DECLARATIONS
@parameters t x1 x2 x3 x4
@variables u(..)
Dt = Differential(t)
Dx1 = Differential(x1)
Dx2 = Differential(x2)
Dx3 = Differential(x3)
Dx4 = Differential(x4)
Dxx1 = Differential(x1)^2
Dxx2 = Differential(x2)^2
Dxx3 = Differential(x3)^2
Dxx4 = Differential(x4)^2
# Discretization
tmax = 1.0
x1width = 1.0
x2width = 1.0
x3width = 1.0
x4width = 1.0
tMeshNum = 10
x1MeshNum = 10
x2MeshNum = 10
x3MeshNum = 10
x4MeshNum = 10
dt = tmax / tMeshNum
dx1 = x1width / x1MeshNum
dx2 = x2width / x2MeshNum
dx3 = x3width / x3MeshNum
dx4 = x4width / x4MeshNum
domains = [t ∈ Interval(0.0, tmax),
x1 ∈ Interval(0.0, x1width),
x2 ∈ Interval(0.0, x2width),
x3 ∈ Interval(0.0, x3width),
x4 ∈ Interval(0.0, x4width)]
ts = 0.0:dt:tmax
x1s = 0.0:dx1:x1width
x2s = 0.0:dx2:x2width
x3s = 0.0:dx3:x3width
x4s = 0.0:dx4:x4width
λ = 1.0f0
# Operators
Δu = Dxx1(u(t, x1, x2, x3, x4)) + Dxx2(u(t, x1, x2, x3, x4)) + Dxx3(u(t, x1, x2, x3, x4)) + Dxx4(u(t, x1, x2, x3, x4)) # Laplacian
∇u = [Dx1(u(t, x1, x2, x3, x4)), Dx2(u(t, x1, x2, x3, x4)), Dx3(u(t, x1, x2, x3, x4)), Dx4(u(t, x1, x2, x3, x4))]
# Equation
eq = Dt(u(t, x1, x2, x3, x4)) + Δu - λ * sum(∇u .^ 2) ~ 0 #HAMILTON-JACOBI-BELLMAN EQUATION
terminalCondition = log((1 + x1 * x1 + x2 * x2 + x3 * x3 + x4 * x4) / 2) # see PNAS paper
bcs = [u(tmax, x1, x2, x3, x4) ~ terminalCondition] #PNAS paper again
## NEURAL NETWORK
n = 10 #neuron number
chain = Lux.Chain(Lux.Dense(5, n, tanh), Lux.Dense(n, n, tanh), Lux.Dense(n, 1)) #Neural network from OptimizationFlux library
indvars = [t, x1, x2, x3, x4] #physically independent variables
depvars = [u(t, x1, x2, x3, x4)] #dependent (target) variable
dim = length(domains)
losses = []
error = []
times = []
dx_err = 0.2
error_strategy = GridTraining(dx_err)
discretization_ = PhysicsInformedNN(chain, error_strategy)
@named pde_system_ = PDESystem(eq, bcs, domains, indvars, depvars)
prob_ = discretize(pde_system_, discretization_)
function loss_function_(θ, p)
params = θ.u
return prob_.f.f(params, nothing)
end
function cb_(p, l)
try
deltaT_s = time_ns()
ctime = time_ns() - startTime - timeCounter
push!(times, ctime / 1e9)
push!(losses, l)
# Extract parameters for loss calculation
params = p.u
loss_ = loss_function_(p, nothing)
push!(error, loss_)
timeCounter += time_ns() - deltaT_s
return false
catch e
@warn "Callback error: $e"
return false
end
end
@named pde_system = PDESystem(eq, bcs, domains, indvars, depvars)
discretization = NeuralPDE.PhysicsInformedNN(chain, strategy)
prob = NeuralPDE.discretize(pde_system, discretization)
timeCounter = 0.0
startTime = time_ns() #Fix initial time (t=0) before starting the training
res = Optimization.solve(prob, minimizer, callback=cb_, maxiters=maxIters)
phi = discretization.phi
params = res.minimizer
# Model prediction
domain = [ts, x1s, x2s, x3s, x4s]
u_predict = [reshape([first(phi([t, x1, x2, x3, x4], res.minimizer)) for x1 in x1s for x2 in x2s for x3 in x3s for x4 in x4s], (length(x1s), length(x2s), length(x3s), length(x4s))) for t in ts] #matrix of model's prediction
return [error, params, domain, times, losses]
end
maxIters = [(1,1,1,1000,1000,1000,1000),(1,1,1,300,300,300,300)] #iters for ADAM/LBFGS
# maxIters = [(1,1,1,1,1,2,2),(1,1,1,3,3,3,3)] #iters for ADAM/LBFGS
strategies = [NeuralPDE.QuadratureTraining(quadrature_alg = CubaCuhre(), reltol = 1e-4, abstol = 1e-4, maxiters = 1100),
#NeuralPDE.QuadratureTraining(quadrature_alg = HCubatureJL(), reltol = 1e-4, abstol = 1e-4, maxiters = 1100, batch = 0),
NeuralPDE.GridTraining(0.1),
NeuralPDE.QuadratureTraining(quadrature_alg = CubatureJLh(), reltol = 1e-4, abstol = 1e-4, maxiters = 1100),
NeuralPDE.QuadratureTraining(quadrature_alg = CubatureJLp(), reltol = 1e-4, abstol = 1e-4, maxiters = 1100),
NeuralPDE.GridTraining(0.2),
NeuralPDE.StochasticTraining(400 ; bcs_points= 50),
NeuralPDE.QuasiRandomTraining(400 ; bcs_points= 50)]
strategies_short_name = ["CubaCuhre",
"HCubatureJL",
"CubatureJLh",
"CubatureJLp",
"GridTraining",
"StochasticTraining",
"QuasiRandomTraining"]
minimizers = [Optimisers.ADAM(0.005),
#BFGS()]
LBFGS()]
minimizers_short_name = ["ADAM",
"LBFGS"]
#"BFGS"]
# Run models
error_res = Dict()
domains = Dict()
params_res = Dict() #to use same params for the next run
times = Dict()
losses_res = Dict()
```
## Solve
```julia
print("Starting run")
## Convergence
for min =1:length(minimizers) # minimizer
for strat=1:length(strategies) # strategy
# println(string(strategies_short_name[strat], " ", minimizers_short_name[min]))
res = hamilton_jacobi(strategies[strat], minimizers[min], maxIters[min][strat])
push!(error_res, string(strat,min) => res[1])
push!(params_res, string(strat,min) => res[2])
push!(domains, string(strat,min) => res[3])
push!(times, string(strat,min) => res[4])
push!(losses_res, string(strat,min) => res[5])
end
end
```
```julia
#Plotting the first strategy with the first minimizer out from the loop to initialize the canvas
current_label = string(strategies_short_name[1], " + " , minimizers_short_name[1])
error = Plots.plot(times["11"], error_res["11"], yaxis=:log10, label = current_label)#, xlims = (0,10))#legend = true)#, size=(1200,700))
plot!(error, times["21"], error_res["21"], yaxis=:log10, label = string(strategies_short_name[2], " + " , minimizers_short_name[1]))
plot!(error, times["31"], error_res["31"], yaxis=:log10, label = string(strategies_short_name[3], " + " , minimizers_short_name[1]))
plot!(error, times["41"], error_res["41"], yaxis=:log10, label = string(strategies_short_name[4], " + " , minimizers_short_name[1]))
plot!(error, times["51"], error_res["51"], yaxis=:log10, label = string(strategies_short_name[5], " + " , minimizers_short_name[1]))
plot!(error, times["61"], error_res["61"], yaxis=:log10, label = string(strategies_short_name[6], " + " , minimizers_short_name[1]))
plot!(error, times["71"], error_res["71"], yaxis=:log10, label = string(strategies_short_name[7], " + " , minimizers_short_name[1]))
plot!(error, times["12"], error_res["12"], yaxis=:log10, label = string(strategies_short_name[1], " + " , minimizers_short_name[2]))
plot!(error, times["22"], error_res["22"], yaxis=:log10, label = string(strategies_short_name[2], " + " , minimizers_short_name[2]))
plot!(error, times["32"], error_res["32"], yaxis=:log10, label = string(strategies_short_name[3], " + " , minimizers_short_name[2]))
plot!(error, times["42"], error_res["42"], yaxis=:log10, label = string(strategies_short_name[4], " + " , minimizers_short_name[2]))
plot!(error, times["52"], error_res["52"], yaxis=:log10, label = string(strategies_short_name[5], " + " , minimizers_short_name[2]))
plot!(error, times["62"], error_res["62"], yaxis=:log10, label = string(strategies_short_name[6], " + " , minimizers_short_name[2]))
plot!(error, times["72"], error_res["72"], yaxis=:log10, title = string("Hamilton Jacobi convergence ADAM/LBFGS"), ylabel = "log(error)",xlabel = "t", label = string(strategies_short_name[7], " + " , minimizers_short_name[2]))
```
```julia, echo = false
using SciMLBenchmarks
SciMLBenchmarks.bench_footer(WEAVE_ARGS[:folder],WEAVE_ARGS[:file])
```