Skip to content

Commit a603718

Browse files
add example for raw automatic differentiation without special types
#133
1 parent 8625a44 commit a603718

File tree

2 files changed

+45
-0
lines changed

2 files changed

+45
-0
lines changed

docs/make.jl

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -6,6 +6,7 @@ const EXAMPLES_DIR = joinpath(@__DIR__, "..", "examples")
66
const OUTPUT_DIR = joinpath(@__DIR__, "src/generated")
77

88
examples = [
9+
"automaticdifferentiation.jl",
910
"chebyshev.jl",
1011
"disk.jl",
1112
"nonlocaldiffusion.jl",
@@ -36,6 +37,7 @@ makedocs(
3637
pages = Any[
3738
"Home" => "index.md",
3839
"Examples" => [
40+
"generated/automaticdifferentiation.md",
3941
"generated/chebyshev.md",
4042
"generated/disk.md",
4143
"generated/nonlocaldiffusion.md",

examples/automaticdifferentiation.jl

Lines changed: 43 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,43 @@
1+
# # Automatic differentiation through spherical harmonic transforms
2+
# This example finds a positive value of $\lambda$ in:
3+
# ```math
4+
# f(r) = \sin[\lambda (k\cdot r)],
5+
# ```
6+
# for some $k,r\in\mathbb{S}^2$ such that $\int_{\mathbb{S}^2} f^2 {\rm\,d}\Omega = 1$.
7+
# We do this by using derivative information through:
8+
# ```math
9+
# \dfrac{\partial f}{\partial \lambda} = (k\cdot r) \cos[\lambda (k\cdot r)].
10+
# ```
11+
12+
using FastTransforms, LinearAlgebra
13+
14+
# The colatitudinal grid (mod $\pi$):
15+
N = 15
16+
θ = (0.5:N-0.5)/N
17+
18+
# The longitudinal grid (mod $\pi$):
19+
M = 2*N-1
20+
φ = (0:M-1)*2/M
21+
22+
# We precompute a spherical harmonic--Fourier plan:
23+
P = plan_sph2fourier(Float64, N)
24+
25+
# And an FFTW Fourier analysis plan on $\mathbb{S}^2$:
26+
PA = plan_sph_analysis(Float64, N, M)
27+
28+
# Our choice of $k$ and angular parametrization of $r$:
29+
k = [2/7, 3/7, 6/7]
30+
r = (θ,φ) -> [sinpi(θ)*cospi(φ), sinpi(θ)*sinpi(φ), cospi(θ)]
31+
32+
# Our initial guess for $\lambda$:
33+
λ = 1.0
34+
35+
# Then we run Newton iteration and grab an espresso:
36+
for _ in 1:7
37+
F = [sin*(kr(θ,φ))) for θ in θ, φ in φ]
38+
= [(kr(θ,φ))*cos*(kr(θ,φ))) for θ in θ, φ in φ]
39+
U = P\(PA*F)
40+
= P\(PA*Fλ)
41+
global λ = λ - (norm(U)^2-1)/(2*sum(U.*Uλ))
42+
println("λ: $(rpad(λ, 18)) and the 2-norm: $(rpad(norm(U), 18))")
43+
end

0 commit comments

Comments
 (0)